Do I use 3,3V or 5V, when device supports both? I have a general question regarding the power-supply of the electronic components, that are attached to an Arduino.

If I have a device that operates at voltages between 3,3V and 5V (e.g. this RS232 to ttl converter), what is the best way to connect it with the Arduino?

  Connect 3.3V or 5V power supply between VCC and GND

I know, that you can not draw as much current out of the 3,3V Pin like on the 5V Pin. But what if I don't need much current anyways (like in the linked example)?

What ware the advantages / disadvantages of connecting it to 3.3V and 5V?

Using the MAX3232 data sheet , which is what the TTL Converter has on it's board :

The main difference between using 3.3v or 5v is on the receiver data line "R" (or Rout as it is called on the MAX3232).

Simply put, you want to power the TTL converter from the same voltage as your Arduino is using (3.3v or 5v). Meaning the voltage that your I/O pins will put out and accept.

The received data line R will go between 0 volts and Vcc.

You would NOT want to power the TTL converter at 5 volts if you are using the converter for a 3.3v Arduino, as the received data line would go to 5 volts when high. Actually Vcc - 0.1 volts (typ.)  (5 - .1 = 4.9)  as per this specification :

If you power the TTL converter from 3.3 volts, the received data line (Rout) switches between 0v and 3.3v   as shown here :


Cannot receive data from GPS SD Shield V2-B I am attempting to receive GPS data from a GPS SD Shield V2-B purchased from maplin. I have attempted the very simple sketch they provide on their website linksprite.com.
I have also tried following a tutorial found here: http://tronixstuff.com/2014/01/15/tutorial-arduino-mediatek-3329-gps/.
This is the code i am using:

    // Example 19.1

    #include <SoftwareSerial.h>
    SoftwareSerial GPS(2,3); // configure software serial port -

    void setup()
    {
      GPS.begin(9600);
      Serial.begin(9600);
      pinMode(13,OUTPUT);
    }
    void loop()
    {
      byte a;
        if (GPS.available() > 0 )
      {
        a = GPS.read(); // get the byte of data from the GPS
        Serial.write(a);
        digitalWrite(13,HIGH);
        delay(1000);
        digitalWrite(13,LOW);
        delay(1000);
      }
    }

I am using an Arduino 101. The jumpers on the GPS shield are set up as follows:

I have attempted using both power simply from my Mac and an external 9V battery connected to the Arduino.
The 'blink' has been added the sketch to test whether data was being received but there was a problem with the serial monitor. This is not the case because the blink did not occur. It however did occur when moved outside of the if statement as you would expect.
Any help or suggestions would be much appreciated.

You need to set the jumps as per the instructions that came with the shield ...
PAGE4 : short jumpers TX and MRX .... and RX and MTX


How to blink LED's unsynchronized? I'm new to Arduino. For my first project,  I want to make aviation strobe lights. My challenge is to use ONE Arduino to blink both sets of lights. My issue is,  I DON'T want them to be synchronized. I saved a sketch of the blink example from the Arduino IDE software after editing it to do what I want. But, the LED's are synchronized. One LED strobes twice,  while the other strobes once as I want them to. However, they begin their loops together currently and stay synchronized,  which isn't what I want.

So my question is: What is the code I need to write to make each LED blink unsynchronized from the other without having to use 2 Arduino units?

Code:

int led = 11;
int led2 = 12;

void setup() {
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
}

void loop() {
  digitalWrite(led, HIGH);
  delay(50);
  digitalWrite(led, LOW);
  delay(1000);
  digitalWrite(led2,  HIGH);
  delay(50)
  digitalWrite(led2, LOW);
  delay(100) ;
  digitalWrite(led2,  HIGH);
  delay(50)
  digitalWrite(led2, LOW);
  delay(1000);
}

The Arduino Blink example uses delay() to pause the Arduino in a specific state, so that for a specific amount of milliseconds the device will keep the blinkPin HIGH or LOW.

Instead of using a delay(), you should use millis(). The main advantage of millis() over delay() is that it does not interrupt the code. When you call a delay() the whole code pauses, nothing can be done during those milliseconds. But millis() doesn't work that way. You also don't call it the same way as delay().

What millis() does is that it stores a timer value into an unsigned long. At a later point in time you can substract a new millis() from your previously stored millis in the unsigned long. The result is a difference in time between each millis() in milliseconds.

Now, instead of using only one unsigned long, we use two different ones: one for each LED. Now you can log a time interval, independently, for each LED. Furthermore, if you apply the logic of millis() for keeping the LEDs on or off, you don't have to interrupt the code with delay() functions. This means, that regardless of each LEDs state (HIGH or LOW), the timer keeps running, keeps logging and thus can control both LEDs simultaneously.

To give you a bit more information on millis(), below are some references that will get you started in how to implement. If you have more questions, just comment on this answer :)

millis() reference on the Arduino website
Blink without Delay example


Multiple Definition of "_Vectors"? I'm working on an arduino project that uses the GSM Shield and the eHealthSensor from Cooking Hacks. However I ran into an issue in which the interrupt vectors from the header/cpp files used are being defined multiple time.

While I know where the definitions are, I am unsure as to how to circumvent this issue either by Arduino programming or modifying the files since I'm not too experienced in this field. Below are the code for the conflicting files.

Below are the vectors that are in conflict.

PinChangeInt.h

    #ifndef NO_PORTA_PINCHANGES
    ISR(PCINT0_vect) {
        #ifdef PINMODE
        PCintPort::s_PORT='A';
        #endif
        PCintPort::curr = portA.portInputReg;
        portA.PCint();
    }
    #define PORTBVECT PCINT1_vect
    #define PORTCVECT PCINT2_vect
    #define PORTDVECT PCINT3_vect
    #else
    #define PORTBVECT PCINT0_vect
    #define PORTCVECT PCINT1_vect
    #define PORTDVECT PCINT2_vect
    #endif

    #ifndef NO_PORTB_PINCHANGES
    ISR(PORTBVECT) {
        #ifdef PINMODE
        PCintPort::s_PORT='B';
        #endif
        PCintPort::curr = portB.portInputReg;
        portB.PCint();
    }
    #endif

    #ifndef NO_PORTC_PINCHANGES
    ISR(PORTCVECT) {
        #ifdef PINMODE
        PCintPort::s_PORT='C';
        #endif
        PCintPort::curr = portC.portInputReg;
        portC.PCint();
    }
    #endif

    #ifndef NO_PORTD_PINCHANGES
    ISR(PORTDVECT){
        #ifdef PINMODE
        PCintPort::s_PORT='D';
        #endif
        PCintPort::curr = portD.portInputReg;
        portD.PCint();
    }
    #endif

    #ifdef __USE_PORT_JK
    #ifndef NO_PORTJ_PINCHANGES
    ISR(PCINT1_vect) {
        #ifdef PINMODE
        PCintPort::s_PORT='J';
        #endif
        PCintPort::curr = portJ.portInputReg;
        portJ.PCint();
    }
    #endif

    #ifndef NO_PORTK_PINCHANGES
    ISR(PCINT2_vect){
        #ifdef PINMODE
        PCintPort::s_PORT='K';
        #endif
        PCintPort::curr = portK.portInputReg;
        portK.PCint();
    }
    #endif

    #endif // __USE_PORT_JK

GSM3SoftSerial.cpp

// This is here to avoid problems with Arduino compiler
void GSM3SoftSerialMgr::manageMsg(byte from, byte to){};

//#define PCINT1_vect _VECTOR(2)
//#undef PCINT1_vect

#if defined(PCINT0_vect)
ISR(PCINT0_vect)
{
  GSM3SoftSerial::handle_interrupt();
}
#endif

#if defined(PCINT1_vect)
ISR(PCINT1_vect)
{
  GSM3SoftSerial::handle_interrupt();
}
#endif

#if defined(PCINT2_vect)
ISR(PCINT2_vect)
{
  GSM3SoftSerial::handle_interrupt();
}
#endif

#if defined(PCINT3_vect)
ISR(PCINT3_vect)
{
  GSM3SoftSerial::handle_interrupt();
}
#endif

Any advice on how to fix this will be greatly appreciated.

If it helps, I am using an Arduino Mega 2560.

It's linking problem. More .o files included in linking declares identical global symbol eg. ISR(PCINT1_vect). Ideally write own makefile and compile via standard make. As hack you can loook in PinChangeInt.h conditional parts and make global definitions not to avoid *ISR()*s, e.g. #define __USE_PORT_JK


How do I use I2C from an Arduino Uno when I have a GSM shield mounted? This may be an extremely obvious question but I don't seem able to find a definitive answer.

I have an Arduino Uno and a Sim900 GPRS/GSM shield fitted on top of it. I had I2C working on the Arduino to communicate with a Raspberry Pi, but now that I have put the shield on top I can't get the Pi to detect the Arduino. As far as I can tell the SDA and SCL pins on the Arduino aren't being used by the shield so does anyone have any idea how I go about this?

Thanks

There seems to be a number of different Sim900 shields from different suppliers? I suggest you check/post the datasheet of the one you're using. If I2C works without the shield, and does not work with the shield connected , then it seems logical that there is a pin clash.
There is a good Random Nerd Tutorial on getting started with the shield on a Uno. Maybe test it out completely before connecting to the Raspberry Pi?
The Raspberry Pi is 3.3v and the Uno is 5v. You didn't mention level shifting in your question, but it may be worthwhile.


Logic level converter 12v to 5v What is the cheapest and best method to convert 12v(14)<->5V(3.3)? Need to connect Arduino to a car.

I need logical shifter not buck converter to connect Arduino to car 12v circuit. I would like to control electrical equipment of car by Arduino. For example, I want to connect input pin to heater, when heater is on from 12v circuit I get HIGH 12v signal which processes by Arduino, but like everyone knows, Arduino can handle only 5/3.3V. Then Arduino going to change state of equipment by connecting optocoupler/relay/transistor to  button(of elect. equip.) and will act like physical press.
P.P.S I know that more clever to hack and control by CAN bus. But not all eq. are connected to CAN bus and it`s a little bit risky but I'm working on it as well.
I'm looking for best low cost solution. I have found it on ebay . Will it work like I want? Offer DIY solutions as well.

Ok, so... I can see your question is a bit obscure, so I'll try to cover a generic approach.

Power If you need to power the arduino, you can get a cheap car USB adapter. If you want a "solderable" solution, I'd avoid linear regulators (such as a 7805)and go with a cheap switching module. For low power applications I usually buy some modules called mini360 (for instance here is a link from aliexpress) which are cheap and ok for even some hundreds of milliamps. You FIRST turn the potentiometer to set the output voltage (checking with a multimeter) and THEN connect the arduino to it.
Get status If you need to get the status of something (e.g. whether the lamp is on or off) you have to analyse the circuit. If you have to detect if either 12V or GND are applied, you can solve the problem with a voltage divider. But if the lamp is always connected to 12V and then the GND side is he controlled one then you will always force a (small) current inside it. If this is the case, maybe an optocoupler is the best solution. If the signal is a PWM maybe you need some filtering, if it is a digital wire maybe it is already at the correct voltage, .... You have to figure out what is the best solution for you
Set status If you need to control something (e.g. turn on a light) your best bet is to use a 5V relay. There are plenty of them, even modules with the transistor and diode necessary to control them with an arduino.

Here are some ideas and rough schematics for the three points

simulate this circuit – Schematic created using CircuitLab

Just one very big WARNING: you have to carefully double check that the modification does not blow something up (for instance, you can make a short circuit if the body computer tryes to force a wire to 12V and you close the relay to ground). So... Be very careful, since what you do can break a lot of things, and if you are very lucky the bill can be only some couple of thousand dollars (I'll let you figure out what happens if you are not lucky enough)


What are the unused pins in an Arduino L293D motor shield? What are the unused pins in an Arduino L293D motor shield? I want to connect the shield using wires instead of directly mounting on top of the Arduino board.

Check out this Link. Here, you can find this explanation in Code. I hope it will helpful for you.

Pin usage with the Motorshield
---------------------------------------
Analog pins: not used at all...
A0 ... A5 are still available...
They all can also be used as digital pins.
Also, I2C (A4 = SDA and A5 = SCL) can be used.
These pins have a breadboard area on the shield.
Digital pins: used: 3,4,5,6,7,8,9,10,11,12
Pin 9 and 10 are only used for the servo motors.
Already in use: 0 (RX) and 1 (TX).
Unused: 2,13
Pin 2 has an soldering hole on the board, easy to connect a wire.
Pin 13 is also connected to the system led.
I2C is possible, but SPI is not possible since those pins are used.


MAX72XX with 8 digit 7 segment display library A while ago, I found a library for the MAX72XX that had functions for writing text to the display, but unfortunately cannot find such library now.

Which would be the best library to use for a text and number display? I'm using LedControl but it is very awkward to use.

I have a library for driving the MAX7219 chip connected to a 7-segment display. It is at: https://github.com/nickgammon/MAX7219

Example of use:

#include <SPI.h>
#include <bitBangedSPI.h>
#include <MAX7219.h>

const byte chips = 1;

// 1 chip, bit banged SPI on pins 6, 7, 8
MAX7219 display (chips, 6, 7, 8);  // Chips / LOAD / DIN / CLK

void setup ()
  {
  display.begin ();
  display.sendString ("HELLO");
  }  // end of setup

void loop () { }

In operation displaying a number:

More details at: Interfacing LED displays with the MAX7219 driver


Connecting a USB 3.0 Flash Drive Is it possible to connect the nine pins from a USB 3.0 memory drive to the corresponding GPIO pins of the arduino (intel Galileo is what I am using, but it is very similar) and access the drive's memory through the implementation of the USB's protocol? I have searched around and have not been able to get a clear idea on how to do this or if it is even possible.

Since this is going to be a long post, I'll post the summary above the fold to save some of you the effort of scrolling...

tl;dr: No, it's not possible to do so with GPIO pins. There is another way to do this, but IDK if the rest of the Galileo will be a bottleneck (and it's pretty pricey). The stereotypical AVR Arduino is simply too underpowered (both from a MCU and amperage standpoint) to host USB 3.0. You need a shield to host USB 2.0, and even with that, I doubt that you can use 2.0 at it's full potential.

Basic corrections/things to note (before I begin):

Note: I'm no expert on the Galileo, I'm just doing this all from what I remember from what I've read in the past. If you spot an error, feel free to post a comment with a little explanation and I'll fix my post. However, I doubt that there will be any major errors, and the overall content (i.e. the tl;dr) should be fine.
These figures are maximum that I'm posting:

Speed: if speed is near maximums, or even 10%, what's the point of 3.0?
Power: you never know with this one, so account for it being near limits, unless externally powered. Still, don't risk it.

If it's a USB thumb drive, you're going to either get a breakout board for 3.0 and/or break open your device and solder wires onto it. Note that there doesn't seem to be a USB 3.0 breakout board (from a very quick search on Google). I'm also concerned that the wires you would use might not be high enough grade for extreme data transmission.
Only 7 of the 9 lines are used for data. The other two are 5V and GND.
On a Galileo, you'll have to use the 5V selection for the IO pins.
On a Galileo, there's a Mini-PCIe port (although I can't seem to find it in the photos myself). You could add a Mini PCIe to USB 3.0 card. However, that will cost you almost $50 to do so, and by that time it might be better just to seek out another solution.

Photo of it:

Ask yourself do I really need the speed?

No: don't waste the money and the headache.
Yes: consider either another platform or buying this product.

Keep in mind that, although it fits, it probably won't be able to get enough power for true USB 3.0 that your disk needs and drivers will be rare. You for sure will want to research this more before shelling out the cash to buy this card.

Galileo doesn't run a full OS, so I'm highly doubtful that there's drivers.

Like I mentioned before, I'm not quite sure about the Galileo supplying enough power... again you need to check into this and maybe add an external voltage regulator (if all the other issues are resolved). USB 3.0 can provide up to 2x the power per port of 2.0, so when I say almost an amp, it's technically almost two amps (although I think at this point you'll just have to remember not to use the second port and call it one amp).

Technical problems:

I stated this before in the post:

  The stereotypical AVR Arduino is simply too underpowered to host USB 3.0. You need a shield to host USB 2.0, and even with that, I doubt that you can use 2.0 at it's full potential.

The Galileo has native 2.0 support, so I'd recommend just getting a fast USB drive and using that.

Anyway, think about it: the Galileo can handle roughly 400,000 instructions per second. USB 3.0 can send up to 5,000,000 bits in the same amount of time! Like mentioned before, it is the maximums, but still. AFAIK on the AVR boards it it takes multiple instructions to read one GPIO pin (for some reason I want to say 3, but that seems too low). I'd imagine that it'd be the same situation on the Galileo. I'm not quite sure about the instructions it takes to read a pin, correct me if I'm wrong anyone. Anyway, assume it takes four instructions per pin, and your device only sends 1 Gbps. That's still 1,000,000 times that a pin needs to be read when you can only read 100,000 in that time. Even so, you can't even use the data, nor can you implement a loop or other code that combines bytes to read the data in the first place! Plus, you wouldn't have enough RAM!

I'm not a USB expert, but IIRC it only asks the device for data as needed, but still, that'd be pointless to create your code for this and spend the extra money for 3.0 cables and devices. This paragraph is all from memory, I don't really know; don't cite this paragraph.

Also, you'd have to implement your own code for sending data to/from the device. No such code exists without hardware for 2.0, let alone 3.0.

Conclusion:

It's near impossible to do so, and you'd need a lot of extra parts and have to read up on the USB 3.0 specs. I think it would take a great engineer 50+ years to accomplish this without developing an IC (which would cost money). Do you really need the speed? If not, you can buy USB 2.0 host shields and communicate via SPI. That isn't very fast, but still, it's possible.

Sources:

Info and photos are scattered on the following sources:

http://en.wikipedia.org/wiki/USB
http://arduino.cc/en/ArduinoCertified/IntelGalileo
http://www.amazon.com/StarTech-com-Express-SuperSpeed-Adapter-MPEXUSB3S2/dp/B004NO0LK8


Arduino UNO GPS module I am thinking about buying a gps module for Arduino UNO.

I would like to install it on a self-build RC-car which is also controlled by Arduino.
The problem is, I cannot install the gps module on the top of the car (on the surface), only the bottom and or/middle space is "free".
My questions are:

1)Is there a module which can overcome a small layer of steel (max 2cm thick) and some plastic and still get a good signal?

2)It would be nice to be able to store the data into a memory card.

3)It would be a great plus to be able to gather data real-time through some kind of connection. Sadly I do not know how to do here. Is there some place where I can look up any of this?

Do you think that this http://www.adafruit.com/products/1272 is what I need?

thank you

1) Just break out the headers on the GPS module to make for connections to the UNO.

2) Add a SD expansion slot on top of the GPS Module and break out the pins for those as the required pins for those as well.

3) I am not sure what you are asking exactly, but it seems to me that you want to analyze the data real-time.  Get a network shield and make sure you can SSH into it through another computer.

Note: When I say "break out the pins", I am simply saying either solder on some extra headers, or wires.


Arduino add two spi slaves that has no slave select pin I am working on a project where Arduino is communicating with two devices using SPI. Unfortunately, these two devices has no ss(slave select) pin to communicate with each one separately.

How Can I solve this issue?

Sensor example

Thanks

Ss or cs pin ISS not mandatory for SPI.

A few solutions.

Power on or off the devices. A group pin can do that.
Cut off mclk.
Have a separate sclk pins for individual chips. You will need to share the serial data pins, ored with some diodes or pull up.
Software SPI.

...

I'm sure others will come up with more solutions.


Multi-threaded Robot I am working on a small robot project, the code which i made for this has a sequential execution in a single thread. There are a lot of Delay() function needed. Due to which the accuracy is extremely bad.
i want to to implement the movements in one thread and the sensor detection in another thread.

#define M1 3
#define M2 5
#define M3 6
#define M4 9
#define L_trig 2
#define L_echo 4
#define R_trig 7
#define R_echo 8
#define servo 10
#define solenoid_pin 11
#define LDR_pin1 12
#define LDR_pin2 13
void setup()
{
// Motors Initilization
pinMode(M1,OUTPUT);
pinMode(M2,OUTPUT);
pinMode(M3,OUTPUT);
pinMode(M4,OUTPUT);
// Ultrasonic  Initilization
pinMode(L_trig, OUTPUT);
pinMode(L_echo, INPUT);
pinMode(R_trig, OUTPUT);
pinMode(R_echo, INPUT);
S.attach(servo);
}

void loop()
{

 Runmotor(M1);
 Runmotor(M2);
 Runmotor(M3);
 Runmotor(M4);
 servo_rotation();
 Ultrasonic_value(L_trig,L_echo);
 Ultrasonic_value(R_trig,R_echo);

 if(Ultrasonic_value(L_trig,L_echo)<5 || Ultrasonic_value(R_trig,R_echo)<5)

   {
     turnLeft();
     //Serial.println("Working");
   }

}

// Run Motor
void Runmotor(int which)
{
  for(int i=0;i<1023;i++)
  {
 analogWrite(which, i);
  }
}
// Stop Motor
void stopmotor(int which)
{
  digitalWrite(which,LOW);
}
// To turn the robot left side
void turnLeft()
{
  stopmotor(M2);
  stopmotor(M3);
  delay(5000);
  Runmotor(M2);
  Runmotor(M3);
}
// To turn the robot Rightside
void turnRight()
{
  stopmotor(M1);
  stopmotor(M4);
  delay(5000);
  Runmotor(M1);
  Runmotor(M4);
}
// Servo Rotation
void servo_rotation()
{
 for(angle=0;angle<=180;angle++)
{
 S.write(angle);
 if(angle==90)
 {
   delay(2000);
 }
}
delay(2000);
for(angle=180;angle>=0;angle--)
{
  S.write(angle);
  Serial.println(angle);
  if(angle==90)
 {
   delay(2000);
 }
}
 delay(2000);
}

// Calculation of distance
long Ultrasonic_value(int which_trig,int which_echo)
{
  long duration, distance;
  digitalWrite(which_trig, LOW);
  delayMicroseconds(2);
  digitalWrite(which_trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(which_trig, LOW);
  duration = pulseIn(which_echo, HIGH);
  // distance = duration*343*100/2;
  distance = (duration/2) / 29.1;
  delay(100);
  return distance;
}

void Solenoid_Fire()
{
  digitalWrite(solenoid_pin,LOW);
}

void Solenoid_Reload()
{
  digitalWrite(solenoid_pin,HIGH);
}
/*
bool LDR_reading(int LDR_pin1 , int LDR_pin2)
{

}
*/

Please help me. I want to implement this code in a Multi-thread fashion. Thanks in Advance

You could also give my ThreadHandler library a try

https://bitbucket.org/adamb3_14/threadhandler/src/master/

It uses an interrupting scheduler to allow context switching without relaying on yield() or delay().

I created the library because I needed three threads and I needed two of them to run at a precise time no matter what the others were doing. The first thread handled serial communication. The second was running a Kalman filter using float matrix multiplication with the Eigen library. And the third was a fast current control loop thread which had to be able to interrupt the matrix calculations.

How it works

Each cyclic thread has a priority and a period. If a thread, with higher priority than the current executing thread, reaches its next execution time the scheduler will pause the current thread and switch to the higher priority one. Once the high priority thread completes its execution the scheduler switches back to the previous thread.

Scheduling rules

The scheduling scheme of the ThreadHandler library is as follows:

Highest priority first.
If the priority is the same then the thread with the earliest deadline is executed first.
If two threads have the same deadline then the first created thread will execute first.
A thread can only be interrupted by threads with higher priority.
Once a thread is executing it will block execution for all threads with lower priority until the run function returns.
The loop function has priority -128 compared to ThreadHandler threads.

How to use

Threads can be created via c++ inheritance

class MyThread : public Thread
{
public:
    MyThread() : Thread(priority, period, offset){}

    virtual ~MyThread(){}

    virtual void run()
    {
        //code to run
    }
};

MyThread* threadObj = new MyThread();

Or via createThread and a lambda function

Thread* myThread = createThread(priority, period, offset,
    []()
    {
        //code to run
    });

Thread objects automatically connect to the ThreadHandler when they are created.

To start execution of created thread objects call:

ThreadHandler::getInstance()->enableThreadExecution();


Why don't these sketches produce a similar output? I compiled the following two sketches with the compiler used by the Arduino IDE and ran them on an Arduino UNO (smd edition).
I'm using:

Arduino IDE v. 1.8.0
Arduino AVR Boards v. 1.6.20

1.

void setup() {

  Serial.begin(115200);
  unsigned long a, b;
  //unsigned long c, d;

  a = micros();
  for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
  b = micros();
  Serial.println(b - a);

  //c = micros();
  //for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
  //d = micros();
  //Serial.println(d - c);

}

void loop () {}

2.

void setup() {

  Serial.begin(115200);
  unsigned long a, b;
  unsigned long c, d;

  a = micros();
  for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
  b = micros();
  Serial.println(b - a);

  c = micros();
  for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
  d = micros();
  Serial.println(d - c);

}

void loop () {}

These were the outputs on the serial monitor:

2452320
3332640
 3332704

Why did each of the two for loops in the second sketch take roughly 33% more time to execute than the loop in the first one?

The different time implies different (number of) instructions being executed.  This is most probably due to the crappy GCC compiler optimizations.

In the former sketch, probably the compiler manages to use only registers, which are very fast. In the second one, the compiler THINKS it needs 8 more bytes, and there are no registers left, so it uses the stack (internal RAM) to store some variables, which is slower. (still, the optimizer should realize that in fact it don't need more bytes, because a and b are not used after the first println()). To access to a SRAM location, you need a LOAD/STORE operation, which takes a longer time, with respect to an operation between registers (beside having to load the memory address to X, Y o Z).
Probably, the compiler is even crappier, because, instead of putting the rarely-used variables a,b,c,d on the stack, it puts i (which is always incremented) or other variables used in digitalRead().

Still, to explain where is the trouble (i.e. where compiler fails in optimizing the register allocation/usage), you should disassemble the object code. Use for instance Atmel Studio, which still uses GCC, but has a good debugger, disassembler and cycle-exact analysis.

Still, this is very strange, perhaps optimizations were not enabled the platform.txt of your arduino?

EDIT:
Using Arduino 1.8.0, I tested the two sketches and analyzed the lss (generated using avr-objdump). The compiler optimizes a lot more the first code. Instead of making a CALL to digitalRead() (as it happens in the second sketch) it probably recognizes that such function is called only once on the code. Therefore it makes a rjmp to it. At the end of that function, there won't be a RET but a branch to the point where i is computerd and checked (actually i is not incremented, actually gets decremented and checked against 0).

In other words, even if the two codes are equal (except that the second sketch runs the same code twice), they are compiled (optimized) differently.


Burning servos like crazy, what am I doing wrong? For some reason my servos keep burning out.

My code is simple, if condition, rotate to 0 degrees, else rotate to 180.

However, what that does to the motor is keep it in a constant struggle to stay in rotation 0 or 180, when there is no movement in between. Sure enough, leave it running for 1 hour, the motor burns out.

if (!strcmp("1",output)){
    myservo.write(0);
}
else {
    myservo.write(180);
}

Is there something like myservo.release or something? I presuming i need to get the servo in to position, then release it so it doesnt try to stay in position.

Please help, i've burned through 4-5 of them so far, it's not fun :(

Some servos are actually not able to do full 0..180 rotation - or to rephrase it better, the standard 0.5ms and 1.5ms pulse will force them to a position which can not be reached. Therefore the motor keeps on rotating in a constant struggle.

change 0 to something like 20, and 180 to something like 150
check that the motor has stopped once reaching 20 or 150. I.e. it does not produce any sound, and if you touch the motor body it is not producing any vibration (so no constant stuggle)


Can't use base class and derived class functions I have made two libraries and one test program.I have made my custom uart library.first i have included all functions for printing in single uart library file.but then i have made print library for printing functions only.my files are listed below.i have not posted my code directly so it can be read separately.

uart.h

uart.cpp

print.h

print.cpp

  Test.cpp

#include <avr/io.h>
#include "uart.h"

int main(){
    uart.start(9600);
    uart.print("Test");
}

and i get this error..

  Error

src/print.cpp
src/print.cpp: In member function 'void PrintClass::print(unsigned char)':
src/print.cpp:4:12: error: 'write' was not declared in this scope
write(data);
          ^
src/print.cpp: In member function 'void PrintClass::print(char*)':
src/print.cpp:13:22: error: 'write' was not declared in this scope
write(string[index]);
                   ^
.build/uno/Makefile:47: recipe for target '.build/uno/src/print.o' failed make: *** [.build/uno/src/print.o] Error 1
Make failed with code 2

i have referred default arduino libraries like hardwareSerial and LiquidCrystal and i made my library like that but i cant get rid of that.
Please Help me.

Any functions that the base class needs to call that will be defined in the child class must also be defined in the base class.  They should be defined "virtual" so they can be overridden, and can even be "pure virtual" so they have to be defined in the child class.

So for any function in the child class that the base class needs to access, add this to the base class's definition (print.h):

virtual void write(unsigned char data) = 0;

The = 0 bit defines it as pure virtual, and any classes than inherit this class without defining their own copy of the void write(unsigned char) function will thrown an error.

Instead of pure virtual you can provide a default function that a child can override if they want to, which can be useful if most classes will work the same way (define it in the parent) but some want to do it differently (override it in the child), in which case you treat it like a normal class function but add the virtual tag.

The whole topic is called polymorphism and is an incredibly powerful system.  It's discussed in detail here: http://www.cplusplus.com/doc/tutorial/polymorphism/


I want turn the led off only when the input is low for a prolonged period of time and not when there are ups and downs in sound signal My project is baby cry detection,when the baby cries the led must turn on and when it stops it should turn off, but I want it to turn off only when the baby has stopped crying , not when there are ups and downs in the sound . When there is a high in baby sound the led turns on and when there is low the led turns off.  I want the led to stay on and turn it off only when the baby has stopped crying completely . If the input from sound sensor stays low for a prolonged period of time then the led should turn off , how should I write a code for this condition ?

It's very related to the debounce algorithm (used for debouncing switches/keys), but consider a button 'bounce' as a cry. The time is much longer (seconds, to even minutes).

See here the debounce explanation:

https://www.arduino.cc/en/tutorial/debounce

As soon as the baby starts crying, you want the LED to be turned on (almost) immediately, so use a short 'debounce' (or in this case: cry on) time for a rising edge (start crying), something in ms or a second maybe (I assume it is that time critical).
However, for detecting stopping crying, you probably want a much longer time, maybe even a minute (but I leave the exact timing requirement up to you).


NTP rollover-safe design with ESP8266 (Curiosity) The Arduino NTP implementation is rather naive in some respects. It basically just grabs the time in seconds from the raw packet, and then converts it to Unix time via subtraction. How would it be possible to create an implementation that is safe from at least this next NTP rollover (due in 2036)? I'd rather not design something that might suddenly fail in strange ways in a decade or two when I have forgotten why it might do so (but it's not horribly important if it's not easily fixed).

If it can make it to 2100, I'd have larger problems (the RTC would crap itself), so just this rollover is fine.

The existing implementation (https://github.com/arduino-libraries/NTPClient/blob/master/NTPClient.cpp):

unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]);
unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;

this->_currentEpoc = secsSince1900 - SEVENZYYEARS;

This implementation is perfectly fine. The calculations are done with
unsigned numbers, so they are naturally rollover safe. The day NTP time
rolls over, secsSince1900 will become a very small number, and
subtracting SEVENZYYEARS from it will cause an extra roll over. Owing
to the rules of modular arithmetics, these two rollovers compensate and
you are guaranteed to get the correct result modulo
232 s.

In the end, you get a Unix time as an unsigned 32-bit integer. Unix time
is traditionally signed, which makes the 32-bit representation roll over
in January 2038. The authors of this library have instead chosen to
represent it as an unsigned number, which means it will roll over in
February 2106.


Feed values to an array using keypad interfaced with Arduino Uno I am trying to input keypad values to an array. The code compiles without any error. When running the code, the code proceeds into the for loop and prints 'm' on the lcd, but doesn't execute "customKey = customKeypad.getKey();" and the below steps and keeps printing 'm' 5 times. I am not able to enter keypad values. Please help.

#include <LiquidCrystal.h>
#include <Keypad.h>

const int rs = A1, en = A0, d4 = A2, d5 = A3, d6 = A4, d7 = A5;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

const byte ROWS = 4;
const byte COLS = 4;

char hexaKeys[ROWS][COLS] = { { '1', '2', '3', 'A' }, { '4', '5', '6', 'B' }, {
    '7', '8', '9', 'C' }, { '*', '0', '#', 'D' } };

byte rowPins[ROWS] = { 13, 12, 11, 10 };
byte colPins[COLS] = { 9, 8, 7, 6 };

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS,
    COLS);

//String inputString = "";
char customKey;
char a[5];

void setup() {
  Serial.begin(9600);
  //inputString.reserve(200);
  lcd.begin(16, 2);
}

void loop() {
  lcd.clear();
  if (Serial.read() == '1') {
    lcd.setCursor(0, 0);
    lcd.print("WELCOME !");
    delay(1000);
    lcd.clear();
    lcd.print("Enter UserID :");
    lcd.setCursor(0, 1);
    for (int i = 0; i < 5; i++) {
      lcd.print('m');
      customKey = customKeypad.getKey();
      delay(30);

      if (customKey) {
        lcd.print('*');
        a[i] = customKey;
      }
      if (i == 5) {
        a[i] = '\0';
        break;
      }

      delay(1000);
    }
  }
}

customKeypad.getKey(); doesn't wait for the key press. it returns 0 if no key is pressed.

you should rewrite the sketch to a version where the loop() can loop and key presses are read as they are pressed.


How to display a number using SevSeg library on 4 digit 7 segment LED display I am getting error with this. It is displaying those segments which are not to be displayed, i.e., 3.141 is dark and other segments are red.

#include "SevSeg.h"

SevSeg sevseg; //Initiate a seven segment controller object

void setup() {
    byte numDigits = 4;
    byte digitPins[] = {2, 3, 4, 5};
    byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
    sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(1000);
}

void loop() {
    sevseg.setNumber(3141, 3);
    sevseg.refreshDisplay(); // Must run repeatedly
}

There are two main types of seven segment display:

Common Anode
Common Cathode

The common refers to the fact that one end of the LEDs within a digit are linked, and need to be connected to either Vcc or GND, depending on the type of the display (see below). The other end of each led (one per segment) is used to switch them on, and it is these that go to the Arduino pins, or LED controller.
Common Anode

The common end is connected to the Vcc line. If you wish to light a segment, then the input pin for that segment needs to be pulled LOW.

Source: Four multiplexed 7-segment COMMON ANODE LED
Common Cathode

The common end is connected to the GND line. If you wish to light a segment, then the input pin for that segment needs to be pulled HIGH.

It sounds as if you have the logic inverted, so the wrong segments are lit, when they should be dark, and vice versa.
Either that, or you need to invert the logic in your code, and for example if you are currently pulling a pin LOW to light up a segment, then you need to change your code to pull the pin HIGH.

Image sources:
Electronics-Tutorials
Common Anode/Cathode 7-segment displays


It is possible to program Linino to send HTTP requests and then use the returned values in sketch? I am new to using Arduino Yun and I would like to know if it is possible to run a command from the Arduino sketch in order to make (probably, through the Bridge Library) Linino to execute a HTTP Request to a remote server. Then I would like to know if it is possible to use the returned values in that Arduino sketch.

In other words, I would like to delegate the task of retrieving values from the web to the Linux side and the usage of the retrieved data to the sketch.

If it is possible, how to do that?

Take a look at Bridge example or TemperatureWebPanel example: you see you can receive kind of "commands" and react "doing things".

Then take a look at HTTP Client example, where you delegate an HTTP call to the linux side.

Now mix the two: you can make HTTP calls after receiving a command from outside your Yun.

A short test can be done by cutting and pasting the examples above.


Float array to comma separated string I have a loop command reading temperature sensor data from 8 thermistors and are storing them as floats into an array. Instead of printing to Serial on each iteration, I would like to create a comma separated string of these values and send to serial (in one instance, versus 8). What would be the best way to do this? I have tried sprintf commands to no avail.
Thanks in advance!
Edit: I would like to also write this string of comma separated values to a MicroSD card slot so I am under the assumption that creating the string once and printing to Serial AND saving to MicroSD card is more efficient than 8 separate iterations

Basic Arduinos have no support for floating point in sprintf and related functions.
Instead you have to use dtostrf() to build up a string block by block.
However there is no benefit to building a string then outputting to serial "in one instance" compared to outputting the data a bit at a time.  Serial is slow. Very slow. When you "output" data to serial you aren't outputting data. You're merely putting the data into a buffer to be sent when it's possible.
In effect, by using multiple Serial.print() calls, you're building up the string to send in the Arduino's internal serial TX buffer.
By building the string first all you're doing is creating a buffer to copy data into a buffer to send it through serial. It's redundant, wasteful, and utterly pointless.


Arduino mini being programmed with CH340G So, I have bought this USB programmer with CH340G chip on it, but it seems, that I cannot program arduino mini clone.

So, this programmer has pinout of 5V|GND|TX|RX|3V3.

I have connected TX to TX and RX to RX (and also switched, because these programmers sometimes have marked where certain pins supposed to go, not what they represent).

I have also wired the DSR leg from the chip and connected it to the RESET on arduino mini clone.

There's still no connection between them.

Now I'm wondering, if I just connect the power supply and TX and RX connectors, when am I supposed to press reset for the succesfull programming?

First of all you should connect the DTR (not the DSR) pin to the reset terminal WITH a 100nF capacitor. See this page or the arduino uno schematics to see how to put the capacitor (it's simply in series with the signal.

However I suggest you to start programming WITHOUT the autoreset; once you are sure that you can program it then try soldering that capacitor to program the arduino without having to hit the reset button.

As for when, watch the IDE status: when it stops compiling and shows the "Uploading" string, press the reset button on the board. You will usually have a couple of seconds to press it.


Wired IoT sensor network with PoE? Objective: Maybe I'm a bad Googler, but I am finding very little on wired Internet of Things sensor networks using Arduino.

Project Goals:

Arduino based sensor nodes that connect to the local network (not out to the internet)
All the benefits of adding adding/removing nodes, moving nodes, adding new routers for more ports.
Black box sensors that don't take any soldering to plug into the network (although they contain soldered components in the black box.
Using a master Raspberry Pi on the network to identify the nodes and read data from them.
Using Power over Ethernet (PoE) to power my sensor nodes.
Don't want to actually connect to the outside internet, just want the convenience of assembling a network with node names and such.

Why not use wireless solutions (e.g. XBee):

Currently, it seems Xbee is the way to go, but I don't want a wireless solution.

I want the reliability of a wired connection.
I don't want to have to worry about batteries

What I'm doing right now:

Currently, I have all my sensors wired to a central Arduino MEGA using 4-conductor security cable (Vcc, GND, and two signal conductors). The MEGA communicates over serial with a Raspberry Pi. This is annoying for the following reasons:

I have to solder/unsolder every time I want to change something.
I have to figure out which digital I/O pins are available on the MEGA and have to write down which signal conductor goes to which pin on the MEGA and means what on the sensor.
There is a finite number of pins.
Each sensor is its own unique project. I want to start standardizing these sensors to clean up the code.

What I have found so far:

I've been looking at XPort sensors; however they are very expensive (i.e. $60 ea.) and don't support PoE. If there is a solution using Arduino and an Ethernet Shield, it brings down the base cost of a sensor by a lot.

Request:

Where can I find out more information about wired Arduino sensors? Are there any prebuilt solutions that already do what I am looking for?

I think I am using a setup like you wish at my home:

PoE Switch (for example Cisco SG300-28P)
Arduino Ethernet's with PoE Module (https://www.arduino.cc/en/Main/ArduinoBoardEthernet) I bought one for every room ;-)
Use DHCP-Server on raspberry PI
Put your sensors on your Arduino ethernet board
I am also using MQTT as protokoll for example http://pubsubclient.knolleary.net/
Use MQTT broker Mosquitto on raspberry pi

For the case that you want to use your switch also for internet connectivity, define a vlan (search wikipedia) for your arduino sensor network.

Hope that helps.


Several SIM with Arduino GSM/GPRS shield For some purpose we need to communicate with Arduino using more that one SIM card, but still like to use an only GSM shield.

So, the idea is to use several SIM holders, to commutate each of six SIM wires to the sim we currently use. But it is still the question

1) How we should handle the gsm module itself? Is it okay for it if the SIM wire will be commutated to another SIM when it is in the middle of something? May be we should power off the module before, but it unclear how to do it programmatically when it is installed on the top of Arduina Mega 2560

2) should we commutate all six wires, or may be there are few signal ones and another shouldn't be never commutated?

3) what is the best way to do this commutation? Relays/transistor switches and so on?

You should reset the shield, and keep reset, while switch sims. The reset is on pin 7.

If you look at the schematic, you can see there are only 3 lines, plus a GND and VDD. The GND and VDD you can probably share between the different sims. The SIM_RST, SIM_SCK and SIM_DATA need to be switched.

I think you should use a MUX for that, but that is not my area of expertise. Note that at least the DATA line is bi-directional.


Error Uploading Arduino Sketch to Arduino Pro Mini I got an error "stk500_getsync() not in sync resp=0x00" when I tried to update an Arduino Pro Mini with an FTDI Basic Breakout 5V/3.3V - Micro USB. Maybe someone has instructions on how to resolve this issue. I use the last version of Arduino IDE.
All standard stuff like drivers, ports installed and configured.

I have communication with controller and I receive answers from it, but when I try to flash the firmware I get that error.

It's your COM port or your board selection.

I often use the Pro Mini and an Uno and when I forget to change either the COM port or the board to which I have to upload the sketch to, that error message happens.


Will a delay() function in a void SerialEvent() also stop the code that is running in the void loop() function? Will a delay() function in a void SerialEvent() also stop the code that is running in the void loop() function?

This is about an Arduino Uno.

This is the main function of the Arduino core:

int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

serialEventRun() runs the serialEvent() function, if it is assigned,
so yes, a delay in serialEventRun will delay the loop.


Strange power comsuption into sleep mode I've finished my project and now I'm measuring the current but there is something wrong. I'm using an Arduino Pro Mini board and the LowPower library but the consumption is about 3.5 - 5 mA and not less than 500 uA (the board remains into sleep mode almost all the time).

When I began to work with the board its LED was removed but I think that this work was not made correctly. How can I check that LED was removed correctly?

Thanks to all.

EDIT1: The strange power consumption is not associated with board's LED.

EDIT2: @Gerben has suggested me to review the state of SPI pins connected to the board. I use in this project a SD card module and GSM/GPRS module but the guilty of this excessive power consumption is the first. Then I've disconnected all SD card module's pins and then I get about 60 uA, so the problem is on those pins but I can't reduce the power consumption. SD card module pins are 10,11,12 and 13 so I've used statements like digitalWrite(10, LOW), digitalWrite(11, LOW) and so on after reading/writing on the SD card but it is useless.

EDIT3: I've decided to upload a representation of my project using Fritzing. The external modules are not identical but they contain the same pins.

General view of the circuit:.

Detail of the connections:

I use these external components:

SD card module
A6 GPRS/GSM module

In my project there are some important details:

GPRS module is powered individually. The other battery is dedicated to power on the Arduino board and the SD card module.
Batteries are 6v.
Transistors base are controlled by 2 and 3 digital pins respectively.
The 8 and 9 pins of the Arduino board act like RX and TX pins using AltSofSerial.h library.

SOLUTION [by OP]

My problem was that the SD card module was consuming when it was controlled by a transistor and my Arduino board was into the sleep mode. So I wrote into the void setup() the digitalWrite(PIN, HIGH) statements where PIN represents all pins connected to the board that belong to the SD card module (DI, DO, CS, and CK pins), to enable the internal resistor of that pins. Then, I checked the power consumption and I reached less than 100 uA.


How to calculating requirements of power supply for a project I am starting with electronics and been working with Arduino for some time now. I did some basic LED and servo motor project and was hoping to jump into making an obstacle-avoidance car. I used 4 AA batteries to make it, but the voltage was too low, as the motors were not moving. Then I knew about the volt requirements and all that. I also tried with a 9v alkaline battery, but it didn't help much.
Here are the electrical parts I used:

Arduino
Ultrasonic sensor
4 toy motor
1 hobby servo motor
Motor driver shield L293D
Battery

These are the operating voltages that I know of:

Arduino = 7 to 12 v
Hobby servo motor =  3.0V~ 7.2V
Toy motor = 3v ~ 12v dc; has a No load current 40 - 80 mA

Because AA batteries are of 1.5v and are in series, it has 6v, and I am assuming that was the reason it was not working as expected. What I am confused about is, how do I choose a battery or power supply to be specific.
Please forgive me for asking such a noob question. Since 1 Arduino + 4 toy motor  + 1 hobby servo motor = 7v + 4 x 12v + 7v = 62 v, but I checked and I couldn't find battery that is above 15v. I surely don't understand how to pick a power supply. Could you please help me out on how to calculate and choose the right battery/power supply? Also, what to look for if for example, I want to run it for a minimum of 10 minutes?

A power supply a 9V battery is not. Since you are using batteries the L293D is a very poor choice for a driver, it uses silicon transistors which I believe are in a darlington configuration which will cause a voltage drop of from 1.4 to 2.8 volt on the motor.  The 4 (or more) AA batteries will work but use a MOSFET bridge. You can always use a small SEPIC (Buck/Boost) converter to power it, that will keep the voltage constant until the batteries are exhausted. Set it to about 9V and power the arduino via the VIN input for more filtering. You will need a way of measuring voltage. You will lose less power with the converter then you are losing in your current driver.


Synchronization and Implementing hamming code on Software Serial I want to learn and use Hamming Code. Would it be wise to
alter the Software serial library to do this or just change the data being
transmitted in the actual Arduino sketch?

Also, for means of better synchronization, what would be the best method with regards to these tx/rx modules working with the Arduino using Software Serial. Am I constrained to using the built in synchronization from the library or may I also implement other forms of synchronization, like manchester and NRZ coding? If so, any guidance here?

EDIT

For implementing Hamming code, what if the interference occurs on the parity bit? Is there a way around this problem?

You can use this info and code: Hamming(8,4) with Arduino.

There's a PDF with documentation about the process of creating a class that implements hamming(8,4) and a link to the source code.

You can use any class that derives from Stream (like Serial or SoftwareSerial).

Edit: If you want to implement a Hamming ECC in a Arduino it would be useful to precompute all the possible message values (you'll find more info at the link above). In a Hamming(8,4) your message is 1byte = 4bits + parity 4 bits; so you must divide your bytes in nibbles. It would be better to put all that stuff (code, decode, manage the upper/lower part of the byte, etc...) in a class. An example using the Hamming class from the link above:

Tx:

#include <hamming.h>

Hamming hamming(&Serial);
char message[] = "Hello World!!";

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

void loop()
{
  hamming.write(message);
  delay(1000);
}

Rx:

#include <hamming.h>

Hamming hamming(&Serial);
char message[Hamming::SIZE];

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

void loop()
{
  if(hamming.isMessageReady())
  {
    hamming.read(message);
    Serial.println(message);
  }
}

If you need to send other kind of info: a float, integer... you can do it, but I think it's a better idea to tokenize/detokenize your information and handle it like a "string".

P.S. You can use any kind of physical layer insofar as it's a child of Stream: Serial, SoftwareSerial...But I've only tested over Serial.


Does 12v 5A power supply is okay to operate motor shield external power I am new to arduino.

Recently purchased motor shield V1.0 which have two l293 and can run 4 DC motors simultaneously.
But here the problem comes: when I purchased the shield I was not aware that it can only supply 2A peak current.
However, my DC motor rating is 12v 5A. So I purchased a 12v 5A power supply.
But now I am not sure to operate shield with external power of 12v 5A.

Does it works or will it burn?

The shield will "burn". You need a shield that can provide minimum 5A per channel to run a 5A motor.

However, your motors aren't 5A. They have a stall current of 300mA, which is well within the capabilities of the motor shield, and the 5A power supply you have would barely even notice they were there.


References (e.g, libraries and tutorials) for connecting the 24-bit ADS1256 ADC to arduino The ADS1256 chip is a high precision 24bit, 8 channel, analog digital converter based on SPI communication that is suitable for biomedical applications and perfect for sensing ECG and EEG signals. I want to hook it up to an arduino, e.g., an arduino mega or an arduino due.

Similar ADCs from analog devices are: ADS1248, ADS1251, ADS1252, ADS1252U, ADS1253, ADS1255, ADS1259, ADS1278, ADS1298, ADS1299, etc.

It’s nice that there are [tiny, coin sized breakout boards]  available for the ADS1256 that include basic components like an 8mhz quartz crystal and cost only around 25 USD.

Several people have in the past struggled to get ADC readings using Arduino. Working only with the data sheet it took them several days or even weeks. I have a logic analyzer, multi channel oscilloscope and bus pirate ready, but I still would prefer adapting an existing library or working with a good tutorial as a starting point.

I searched for code and tutorial not only for the ADS1256 but also for similar analog devices ADC chips.

Here are the tutorials, libraries and information I found so far:

Main Links (working solution):

-- ADS1213 Arduino library (seems to be working!!!)

--  ADS1213 Arduino tutorial (includes above library)

Further Information:

Arduino due ADS129X tools(ADS1299, ADS1298, ADS1294, ADS1296)
ADS1252 Arduino Tutorial
ADS1252 Troubleshooting information
ADS1255 Troubleshooting information
ADS 1298 Troubleshooting information
ADS 1248 and arduino (german)

Q:
Is there a working library for the ADS1256 (or similar chip) and is there a current, up-to-date tutorial available for arduino?

(Update with my notes.)

Next steps (to get a working library that should be put on github):

Search for more relevant Information online (existing libraries, etc.)
Ask in AVR specific forum, if question is unanswered here. Possibly contact people via e-mail that could know more
Get familiar with Chip and Datasheet
Decide on available codebase as the starting point
Define the minimalistic testcase (This would check that some for of communication works with the chip, i.e., write register that changes the logic level of a bin of the ADC chip)
Implement the minimalistic testcase (i.e., possibly use different codebase as starting point if it fails to implement)
Expand and test the code to get a full implementation

Risks: Eittle experience with electronic design the microcontroller at hand, might miss important details that costs a lot of time. Can't be sure that my chip/PCB actually works, can be faulty hardware.

Time Estimate: 3 days of work doing 8 hours a day (total 24 hours). Exremly high variance (could be a matter of a few hours in the best case to a few weeks worst case).

You are lucky. Looks like there is an Arduino library available for the ADS1256. You should give it a shot: https://github.com/Flydroid/ADS12xx-Library .

I haven't tested it but checked the registers and functions from the datasheet and it does look good.


Can Only Upload Arduino Sketch Once to Custom Mega2560 Board I created a custom Arduino based off the Mega2560 R3. It uses the ATMega16U2 uC as the USB interface between ATMega2560 uC and the PC.
The bootloader on the 2560 is uploaded by using an Arduino Micro via ArduinoISP. I followed this tutorial from Instructables on uploading the bootloader/firmware for the 16U2 except I modified some parts for the 2560 instead of the UNO. Here is my added section in the /program Files (x86)/Arduino/hardware/arduino/avr/boards.txt
unorestore.name=MEGA2560 16U2 Restore Firmware
unorestore.bootloader.tool=arduino:avrdude
unorestore.bootloader.low_fuses=0xff
unorestore.bootloader.high_fuses=0xd9
unorestore.bootloader.extended_fuses=0xf4
unorestore.bootloader.file=Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex
unorestore.bootloader.unlock_bits=0x3F
unorestore.bootloader.lock_bits=0x0F
unorestore.build.mcu=atmega16u2
unorestore.build.f_cpu=16000000L
unorestore.build.board=uno.build.board=AVR_MEGA2560
unorestore.build.core=arduino:arduino
unorestore.build.variant=standard

The problem is after I upload a sketch (with a size say over 10 kB), I can't upload any new sketch and get this timeout error message instead as shown below. Not even a simple blink sketch. The TX and RX LED connected to the 16U2 uC that flashes during an sketch upload doesn't even blink once.

The only way I can get it take another sketch is to "re-flash" the bootloader on the 2560 uC via ArduinoISP. The TX and RX led now flashes during the sketch upload. Of course, this is a huge hassle as I don't want to do "re-flash" the 2560 bootloader every time I want to upload a sketch.
I don't have this problem on my Elegoo Mega2560 R3 clone board so I'm thinking it might be something wrong with my 16U2 firmware/bootloader. Anyone have any idea what else might be causing this?

Your RESET circuit is wrong.

You have no pullup resistor on the RESET pin of the ATMega3560.
You have an extraneous pulldown resistor on the D7 pin of the 16U2.

That means your 16U2 will not be able to trigger a reset of the ATMega2560 to run the bootloader.
Remove the pulldown on D7 of the 16U2 and add a 10kΩ pullup to the RESET pin of the ATMega2560. Without that pullup:

The chip may not run properly as RESET is floating (it may have an internal pullup, I can't recall)
The capacitor linking the 16U2 D7 and RESET of the ATMega2560 won't be able to generate a proper reset pulse. This will be exacerbated by the 1kΩ pulldown.

On the Mega2560 reference schematic RN1A is the pullup in question.


Need clarification with arduino syntax I've been learning how to program this fine piece of equipment but i seem stuck. I came upon the "Knight rider" example where you are supposed to blink LED's from one side to another and i can't understand where some of the code comes from. For example:

byte ledPin[] = {4,5,6,7,8,9,10,11,12,13};
int ledDelay;
int direction = 1;
int currentLED  = 0;
unsigned long changeTime;
int pot = 2;
int i;

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

    for (i = 0; i < 10; i++)
    {
        pinMode(ledPin[i], OUTPUT);
    }

    changeTime = millis();
}

void loop()
{
    ledDelay = analogRead(pot);

    if ((millis()- changeTime) > ledDelay)
    {
        changeLED();
        changeTime = millis();
    }
}

void changeLED()
{
    for (i = 0; i < 10; i++)
    {
        digitalWrite(ledPin[i], LOW);
        Serial.print("i = ");
        Serial.println(i);
    }

    digitalWrite(ledPin[currentLED], HIGH);

    currentLED += direction;

    if (currentLED == 9)
    {
        direction = -1;
    }

    if (currentLED == 0)
    {
        direction = 1;
    }
}

In this code I don't  know where the "direction" variable is coming from I searched on the arduino reference page but can't find it. Are there other references where I could look or am I misunderstanding something?

It's coming from the program itself:

int direction = 1;

That means "Create a signed integer called 'direction' and assign it the value 1.


Addressing EACH of the 3x3x3 LEDs separately I read a few 3x3x3 LED tutorials, e.g. let us take this one:

http://www.instructables.com/id/Making-an-Arduino-3X3-LED-Cube-in-Less-Than-30-Min/?ALLSTEPS

As far as I understand, you can address any of the 3x3 light columns:

*  *  *       1  2  3
*  *  *       4  5  6
*  *  *       7  8  9

and each of the three vertical layers:

top
middle
bottom

But can I address each of the 27 leds separately? In other words, can I light up:

1+  2   3         bottom layer
4   5+  6
7   8   9

1   2+  3         middle layer
4+  5   6
7   8   9

No, the three transistors are there to select the layer you want to control. At every moment only ONE layer can be on. But if you switch through controlling these layers fast enough, you can create the illusion of having multiple leds on even across layers. THis is because the human eyes are just not capable of seeing lights flashing at a high rate.

TL;DR
No you can't address them individually, but you can create the illusion that you can.


What is the execution context of the function registered via the Wire.onReceive() method? I'm basically wondering if it's OK to Serial.write() or print in the function I register to be called when I2C data is received.  I can't seem to find the execution context or any warnings.

http://arduino.cc/en/Reference/WireOnReceive

Looking at twi.c in the Arduino libraries, it seems the callback function is called from within the I2C interrupt service routine (ISR). Any code in the call back will lengthen the ISR so it will have to be short. I don't think Serial.write will be too much of a problem; the TX interrupt will be delayed to the end of the I2C ISR which finishes straight after the callback and the Serial.write function is fairly short.

If you need to have a longer function run, you could instead have the callback store bytes in a ring buffer, then check for any available bytes in the main loop().. but this is what the Wire class helps with already.


What is the best way to configure a bidirectional, open collector data pin? I want to communicate with an old keyboard asynchronously through a single open collector, bidirectional data pin. As part of the protocol, the timing will be controlled entirely by pulse width.

I've seen some code examples where the pin is switched from input to output depending on the direction. Without knowing the particular low-level MCU details, however, the approach seems a bit naive. There may be hidden penalties in switching and or calling a function.

Could I share the data line between two pins and set one pin as input and the other as output? Could this work? Are there better methods?

If the other end of the link has the same signal voltage as your
Arduino, you can simulate an open collector with a single pin:

digitalWrite(pin, LOW); pinMode(pin, OUTPUT); sets the pin to output
an active low signal.
pinMode(pin, INPUT_PULLUP) sets the pin to input mode, or output
passive high which, in open-collector mode, is the same thing.

Note that in the first case the order of the commands is important: on
AVR microcontrollers, if you set the mode to OUTPUT before writing
LOW, the pin will for a short time output an active high, which is
forbidden in open-collector mode. I don't know how other MCUs would
behave in the same situation though.

Edit to address Ignacio Vazquez-Abrams’ comment: An open-collector
bus needs a pullup resistor on each data line to function properly. If
that pullup is already provided by your keyboard, or your cable, then
you should use pinMode(pin, INPUT) to accurately emulate an
open-collector output on the Arduino side. Otherwise you have to provide
that pullup, either as an external component or by using the internal
pullup of the MCU. Beware that the latter may be a little bit weak,
depending on your data rate.


Detecting ground distance through rubber I want to put a small Arduino and some sensors inside a tennis ball to measure the ball's height above the ground. It won't be used for tennis, just for fun.

Is there any sensing solution that would allow for the accurate distance detection of the ground through the rubber? Any sort of time-of-flight IR would get absorbed by the rubber that's that thick. I believe sonar would too? My best bet may be using an accelerometer to estimate distance, then determining the height from that.

It may be easier to suggest a solution if you were to "describe the goal" of your project.

If this is just a science experiment, I like your idea of accelerometers.  What you need then is to take the next step and understand dead-reckoning in order to determine the height of the ball.

In other words, the integral of acceleration is velocity.  And the integral of velocity is position.  That means the integral of the integral of acceleration is position. As you may or may not know, for each integral you add a constant. The current speed for the first integral operation and the current position for the second.  But we can assume we can detect hitting the ground.  And, at that point, our position is X = 0 and our velocity is also 0.

That said, dead reckoning is difficult to use mostly because of the accumulated errors.  However, you may have more luck as you get to "reset" your values each time you detect impacting the ground.


Door sensors on every cabinet in the kitchen At this point, I have yet to actually touch an Arduino.  I'm toying with the RPi3 along with Home Assistant, but I'm always thinking of ways to do useless things that are fun.

Let's say I had a kitchen with 32 cabinet doors and drawers and I wanted to make sure that each one had a switch that would detect a simple on/off state.  That would translate to a map whereby a visual indicator would show that something's "ajar."

Is this the best approach to achieve this goal?
How many Arduino boards would this require, and/or are there other methods or concepts to achieve the same ultimate goal?

Thanks!

Touch less sensors (IR, magnetic hall), detecting drawer state.

1pc Arduino with I/O expanders to increase I/O ports.


Why is one part of my code being executed over the part before it? The following code doesn't behave the way I would like it to. Inside the loop function im measuring the distance in front of the robot and if it is less than 15cm than the robot should move back and if it is less than 15cm on the left then move forward. When i run the program however only the left side is being checked and acted upon whilst the the if statement about the front and moving back is not doing anything. Something to note also is that when i swap the if statements and put the front checking ahead of the left checking it works but the left side is no longer being checked. Why is it that the if statement block in front is being executed over the previous one?

     void loop(){

     if(front.calculateDistance() < 15){
     MoveBack(200);
     }else{
      stopMoving();
     }

      if(left.calculateDistance() < 15){
     MoveForward(200);
     }else{
      stopMoving();
     }
   }

This is what the move methods do (move back and stopmoving just change input directions):

void MoveForward(int rspeed) {
 // turn on motor A
 digitalWrite(in1, HIGH);
 digitalWrite(in2, LOW);
 analogWrite(enA, rspeed);
 // turn on motor B
 digitalWrite(in3, HIGH);
 digitalWrite(in4, LOW);
 analogWrite(enB, rspeed);
}

The problem is with your logic. You are saying:

If it's too close in front then move backwards
Otherwise stop all movement
If it's too close on the left then move forwards
Otherwise stop all movement.

That means that if it's too close in front, but not too close on the left, then it will think about moving backwards, but then immediately stop because it's not too close on the left.

You need to think more about the whole space at once, not just one individual direction. For instance, what do you do if it's too close in front and too close on the left? At the moment you'll crash into whatever is in front.

So you should be thinking about four conditions:

Too close in front AND too close on the left
Too close in front BUT NOT too close on the left
NOT too close in front BUT too close on the left
NOT too close in front AND NOT too close on the left.

Then you can choose the right action to perform.

If your specific setup means that it can never be too close in front at the same time as being too close on the left you can collapse it into a simpler form:

IF it's too close in front then move backwards
ELSE IF it's too close on the left then move forwards
ELSE stop all movement.


comparing the entries of two arrays i am trying to compare the elements of two arrays before the code goes on to the next sequence. The elements of note[x] are filled with the note values of a song. and i want to be able to input values from a midi controller into learn[x]. how can i compare array learn[ ]  to array note[ ] before the showsequence(); is incremented?

 const int x = 100;
    int note[x];
    int learn[x];
    int largestindex = 0;
    int learnindex=0;
    void showsequence();
    void readsequnce();
    const int PLAY = 1;
    const int TRYAGIN = 2;
    int state=0;

 void loop() {
     if (state == PLAY) {
        showsequence();
        readsequnce();
      }
      else if (state == TRYAGIN) {
        incorrect();
       }
     MIDI.read();
    }
    void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
    learn[learnindex]=pitch;
     learnindex++;
    }

 void showsequence() {
      //Add a new index to the end of the songseq
      SongSeq[largestindex];
      largestindex++;
      //loop through the songseq
      for (int index = 0; index < largestindex; index++) {
        SongSeq[index]();
      }
    }

      void readsequnce() {
      static uint16_t nextkey;
      bool mademistake = false;
       nextkey=0;
       learnindex=0;

       if (array_cmp(learn, note, largestindex, largestindex) == true){
               // do this if they are equal
               lcd.setCursor(16, 2);
        lcd.print("True");
         }else{
               // do this if they are different
               lcd.setCursor(16, 2);
        lcd.print("False");
         }
    }

 boolean array_cmp(int *a, int *b, int len_a, int len_b){
         int n;

         // if their lengths are different, return false
         if (len_a != len_b) return false;

         // test each element to be the same. if not, return false
         for (n=0;n<len_a;n++) if (a[n]!=b[n]) return false;

         //ok, if we have not returned yet, they are equal :)
         return true;
    }

It depends what sort of comparison you want to do.  If you want to see if note[x] == learn[x] then that's what you do.

If you want to see if all the notes match all of learn then you'll need to put the comparison in a loop.

for (int n = 0; n < MAX_NOTE && note[n] == learn[n]; ++n)
{
    // Empty loop
}

If you want to see if the first n notes match the current note and the proceeding n notes then its a bit more complex, but its just a loop.

int n = 0;
for (int l = currentPos;
(l > (currentPos - 10)) && (note[n] == learn[l]);
 l--, n++)
{
    // Empty loop
}

If it is something else you want, please can you try and describe it in idiot proof terms so I can understand it.


Weird result printing an array using a loop first of all I'm sorry for my english.

My problem is that I want to use an array of numbers on a function, but I'm getting a weird result inside a for loop. Doing some tests I've seen that it happens even in the simplest sketch so I should be doing something wrong.

I've created a two level int and I want to iterate through the second level using a for loop. Outside the for loop all data gotten from that array is OK, but just inside the loop I'm just getting garbage as if the array was not initialized.

My simple sketch is this:

const int number_small[][14] PROGMEM = {
  {124, 124, 387, 387, 399, 399, 443, 443, 483, 483, 387, 387, 124, 124},
};

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

  Serial.print(String(number_small[0][0]) + "\n");
  Serial.print(String(number_small[0][1]) + "\n");
  Serial.print(String(number_small[0][2]) + "\n");
  Serial.print(String(number_small[0][3]) + "\n");
  Serial.print(String(number_small[0][4]) + "\n");
  Serial.print(String(number_small[0][5]) + "\n");
  Serial.print(String(number_small[0][6]) + "\n");
  Serial.print(String(number_small[0][7]) + "\n");
  Serial.print(String(number_small[0][8]) + "\n");
  Serial.print(String(number_small[0][9]) + "\n");
  Serial.print(String(number_small[0][10]) + "\n");
  Serial.print(String(number_small[0][11]) + "\n");
  Serial.print(String(number_small[0][12]) + "\n");
  Serial.print(String(number_small[0][13]) + "\n\n\n");

  for (int i = 0; i<14; i++){
    Serial.print("I: " + String(i) + " - " + String(number_small[0][i]) + "\n");
  }
}

void loop() {
}

And the output is:

124
124
387
387
399
399
443
443
483
483
387
387
124
124

I: 0 - 0
I: 1 - 184
I: 2 - 0
I: 3 - 1
I: 4 - 0
I: 5 - -18248
I: 6 - -18248
I: 7 - -18248
I: 8 - 0
I: 9 - 135
I: 10 - 0
I: 11 - 0
I: 12 - 769
I: 13 - 0

What I'm doing wrong?,

Thanks!!

Constants like String(number_small[0][0]) are optimized by compiler during the build (=compile time).

However that's not the case of loop. So you have to use specific functions for reading values from PROGMEM in the runtime:

for (int i = 0; i<14; i++){
  Serial.print("I: ");
  Serial.print(i);
  Serial.print(" - ");
  Serial.println((int)pgm_read_word(number_small[0]+i));
}

Btw: Don't use string concatenations. These are extremely hungry for the memory. See Majenko's article: The Evils of Arduino Strings


ATmega8L power issue I am doing a prototype using ATmega8L-8PU to detect temperature and control a relay and buzzer, but the schematic seems not work, therefore I do a simple test to verify the AVR's pins are working perfectly or not.

I using the example sketch - Blink to control Digital-13 to let LED blink. It is work.

Then I do a second sketch to test all pins (Due to leak of LED, I test first 8 pins.) It failed. Second Sketch is quite simple and strict forward: blink D0-D7 LED one by one.

char i, j, pcnt = 1;

char startDigitalPin = 0;
char maxDigitalPin = 7;

void setup()
{
    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
    delay(100);

    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
    delay(100);

    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
    delay(100);

    // put your setup code here, to run once:
    for(i=startDigitalPin; i<=maxDigitalPin; i++) {
        pinMode(i, OUTPUT);
        digitalWrite(i, LOW);
    }
}

void loop()
{
    // put your main code here, to run repeatedly:
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);

    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);

    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);

    for(i=startDigitalPin; i<=maxDigitalPin; i++) {
        for(j=i; j<=maxDigitalPin; j++) {
            digitalWrite(j, HIGH);
            delay(100 * pcnt);
            digitalWrite(j, LOW);
            delay(100 * pcnt);
        }

        digitalWrite(i, HIGH);
        delay(200 * pcnt);
    }

    pcnt++;

    if(pcnt > 10) {
        pcnt = 1;
        delay(8000);
    }
}

Question:

Why I using Blink example sketch, D13 is work fine, the LED light on with normal bright.
Why second sketch, the D13 LED super dark, but it light on.

Check it out these 2 videos in youtube.
https://www.youtube.com/watch?v=sknNPxqg5zc
https://www.youtube.com/watch?v=KWsdP3egsvY

I have burn a bootloader to ATmega8L-8PU (Summary Datasheet) using Arduino IDE 1.6.5 with MiniCore, Config: ATmega8 External 8MHz.

Parts in my bearboard using:

ATmega8L-8PU
2 x 22pf
1 x 100nf
1 x 8MHx crystal
9 x LED with 330Ohm resistor

I tested your sketch after adding pinMode(13, OUTPUT) in the setup, and it works as you intended.

But, as you don't post your schematic, I was only able to chech on-board LED blinking.

void setup()
{
  pinMode(13, OUTPUT);

  for (int i=0; i < 3; i++) {
      digitalWrite(13, HIGH);
      delay(100);
      digitalWrite(13, LOW);
      delay(100);
  }

    // put your setup code here, to run once:
    for(i=startDigitalPin; i<=maxDigitalPin; i++) {
        pinMode(i, OUTPUT);
       digitalWrite(i, LOW);
    }
}

I also reduce your code using a for loop.


Press one button then another? Let's say we have two buttons - button 1 and button 2. What I need to do is to do something (like turn LED on) when button 1 is press, then button 2 is pressed. I can do it realy simple by just using two boolean variables, but how can we tell button 1 was the first pressed button?

A nice solution is to use a state variable. In C/C++ (thus Arduino) you can use an enum variable for that.

enum EState
{
  // Button 1 and 2 are not pressed
  NoButtonsPressed,

  // Button 1 is pressed, button 2 is not pressed
  FirstButtonPressed,

  // Both buttons are pressed
  BothButtonsPressed
};

EState _state;

void setup() {
  // put your setup code here, to run once:
  _state = NoButtonsPressed;
}

void loop() {
  // put your main code here, to run repeatedly:
  switch (_state)
  {
  case NoButtonsPressed:
    if (digitalRead(1) == HIGH)
    {
      _state = FirstButtonPressed;
    }
    break;

  case FirstButtonPressed:
    if (digitalRead(1) == HIGH)
    {
      // Button 1 is still pressed, ignore second button.
    }
    else if (digitalRead(2) == HIGH)
    {
      // Button 1 is not pressed, button 2 is pressed.
      _state = BothButtonsPressed;
    }
    break;

 case BothButtonsPressed:
   // Switch on LED
   digitalWrite(2, HIGH);

   // Reset state.
   _state = NoButtonsPressed;
   break;

 default:
   // Other state, illegal.
   break;
  }
}

In every state you can define exactly what needs to be done. Because of the loop function being ran continuously, you just need to handle one state (change) at a time.

Additional notes:

Your requirements are not fully complete (like when to switch off the LED), probably when button 2 is released (which I don't check for), you can add a new state for this.
I did not take debouncing of buttons into account; you might need to do this especially if you check for releasing buttons. On the official Arduino website there is a good article about it.
I haven't tested the sketch.


The use of 4.7kOhm resistor with DS18B20 temperature sensor I was using a temperature sensor DS18B20 with Arduino.

I've read that you should connect the digital input line and the 5V line with a 4.7kOhm resistor - like in the picture.

Can someone explain why do we need to do this? And why this resistance? What happens if we don't put a resistor at all or use a different resistance?

The product page FAQ [https://www.maximintegrated.com/en/support/faqs/ds18b20-faq.html] has an entry:

Q: Is the 4.7kΩ resistor needed for 5V and 3.3V operation?
A: Yes, the 4.7kΩ pullup resistor is required for both 5V and 3.3V applications.

The 1-wire bus requires that the control signal be pulled high so the master device can pull it low to ask for data, and the slave device can pull it low to give the data. This allows you to have multiple 1-wire devices on the same "one wire".

The data sheet notes another purpose:

Another feature of the DS18B20 is the ability to operate
without an external power supply. Power is instead
supplied through the 1-Wire pullup resistor through the
DQ pin when the bus is high. The high bus signal also
charges an internal capacitor (CPP), which then supplies
power to the device when the bus is low. This method of
deriving power from the 1-Wire bus is referred to as “parasite
power.” As an alternative, the DS18B20 may also be
powered by an external supply on VDD.


How to use ESP8266 Pin D3 / GPIO 0 and D8 / GPIO 15 properly I am using WeMos D1 Mini Pro to control multiple relays. I found out that during start up the relay connected to pin D3 and D8 would switch between on and off a couple times in a very short interval. I found out that the two pins are related to boot loader configuration.

Question is: Is there any way to prevent the relay from "blinking"? Is there a way to disable the relay output until boot loader finish it's stuff? Because this behavior only occur once every boot up.

A 74HC244 can be used to buffer up to 8 outputs and isolate them at will from the ESP8266. It can also be used for inputs as well if you connect gates the other way around. One additional IO line is required to control it.


Program size optimization I am trying to spare a few bytes of program size.
I faced a problem which I cannot understand and I hope somebody will help.
Look at this empty sketch, pleas. It takes just 444 bytes:
void setup()
{
}

void loop()
{
}

However, this one – 1332 bytes already!
void f() {
    Serial.println(1);
}

void setup()
{
}

void loop()
{
}

Why?
It is supposed that function f() will be cut-off during the linkage stage. But it is not.
And what can I do to cut such things off, since they are not used in the code?

Using the Serial object pulls HardwareSerial0.o into your program
linkage. This file defines, among other things, the ISRs (interrupt
service routines) associated with the serial port. ISRs are defined
using the ISR() macro from the acr-libc. This macro creates a
function prototype and assigns some attributes to the function,
including the used attribute which tells the linker that it
should consider the function to be used, even if it cannot spot a single
call to it within the compiled program. The ISR cannot then be removed,
and it in turn keeps lots of code from the Serial implementation.
Edit: As pointed out by the busybee in a comment, although f()
cannot be removed at link time, it can be removed at compile time if you
give it the static qualifier. This has the added benefit of triggering
a compiler warning:

warning: 'void f()' defined but not used [-Wunused-function]


How to transmit characters or just use xbee like serial monitor I have an arduino mega and an uno, mega has an xbee s2c as coordinator and uno an xbee s2c as router, both in AT ( transparent ) mode. When I send integers from uno with Serial.write() coordinator receives just fine, but when i try float, negative numbers and chars, i get still integers but as I found out sending chars it is in ASCII. I tried Serial.print() but no result. Is there a way to send a negative float from one xbee to the other in AT mode?

Coordinator code

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial1.begin(9600);
  Serial.println("Comersing test!");
}

void loop() {
  if(Serial1.available()>0){
         Serial.print(Serial1.read());
    }
}`

UNO code

#include <SoftwareSerial.h>
 SoftwareSerial xbSerial(8, 7); // RX, TX
void setup() {
  xbSerial.begin(9600);
  xbSerial.write("First data sent!");

}
int x=4;
void loop() {
  // put your main code here, to run repeatedly:
      xbSerial.write(x);
      x++;
      delay(1000);
      delay(1000);
      delay(1000);
}

if I change x in Uno to float, negative or char, I get weird values.

XBee cannot send negative integers, as it is working in hexadecimal and it has range between 0-255


Windows driver installer not detecting arduino I'm trying to program my Arduino Uno with my Windows PC. I followed all the instructions on the site. I mistakenly downloaded the .zip file and didn't unzip it, before plugging in my Arduino Uno. So naturally, no message came up. I then followed the correct procedure, but Windows driver installer does not detect the Arduino Uno. What can I do to fix this?

Per my comment above, the drivers are not installed when using the Arduino editor from an extracted zip file. If you are feeling adventurous, they are located in the /drivers folder and you can install them manually, there are plenty of instructions elsewhere on the internet on how to do that.

My recommendation would be to just download and run the installer version of Arduino, as that will take care of registering the drivers for you. The installer can be found on the download page indicated with the text "Windows Installer".


Two buttons, one LCD I'm trying to make a program that whenever a button is push, a different word will show on a lCD screen. However, it seems that the two buttons provide the same output ("Screen A"), it's like there is no difference between them, and I'm not sure what's the cause.

The code is very simple:

const int buttonPin1 = 13;     // the number of the pushbutton pin
const int buttonPin2 = 12;     // the number of the pushbutton pin

int buttonState = 0;

long randNumber;

void setup() {

  for(int x=0; x<2; x++)
  {
    pinMode(buttonPin[x], INPUT);
  }

}
    void loop() {

      for(int x=0; x<2; x++)
      {
        buttonState = digitalRead(buttonPin[x]);

        if (buttonState == HIGH && buttonPin[x] == 13) {
          lcd.print("  Screen A ");
        }
        if (buttonState == HIGH && buttonPin[x] == 12) {
          lcd.print("  Screen B ");
        }
      }

    }

Any help is appreciated

I guess it's something with the circuit ... can you add it to your question.

Also, make sure buttonPin has the values 13 and 12 in the first and second index.

Btw, The following code is functionally identical:

void loop()
{
    if (digitalRead(buttonPin[0]) == HIGH)
    {
       lcd.print("  Screen A ");
    }
    if (digitalRead(buttonPin[1]) == HIGH)
    {
       lcd.print("  Screen B ");
    }
}

If you want to have the loop and a flexible amount, use something like:

#define NR_OF_PINS 2

int buttonPins[NR_OF_PINS] = { 8, 9 };
String screens[NR_OF_PINS] = { "Screen A", "Screen B" };

void loop()
{
    for (int pin = 0; pin < NR_OF_PINS; pin++)
    {
        if (digitalRead(buttonPins[pin]) == HIGH)
        {
            lcd.print(screens[pin]);
        }
    }
}

Update

My answer is related to the code before you edited.

Remarks:

After your edited code, you forgot to declare buttonPin:

int buttonPin[] = { buttonPin1, buttonPin2 };
You do not use long randNumber
Instead of a global variable int buttonState  you can create it locally in the loop function (although you do not need it according to my code above).

buttonState = digitalRead(buttonPin[x]);
Also, what you high likely want to add is button debouncing (check the arduino example about this), unless you add a delay after showing a screen of a considerable amount (like 100 ms or more).


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

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.


Arduino and Optoisolators I am looking for an efficient (and safe) way to use the Arduino to switch a higher voltage device off and on. The first option would be a relay, but they are fairly bulky. I was wondering if I should use an Optoisolator instead ?

Here is a link to the Data sheet for the Optoisolator I am using..

http://www.everlight.com/file/productfile/el817.pdf
I think (if I am reading it correctly) it expects an input voltage of 1V at about 20mA ?

However, I think it may be more involved than I originally thought. Here is a sort of simulation of what I am trying to achieve.
http://tinyurl.com/y9xd7lzb

As you can maybe tell, I am using a voltage divider to reduce the output from the arduino (from 5V to 1V).
My concerns are ..

Is this the best approach ?
Is it efficient ?
are there any problems I should be aware of ? Precautions I need to take ?
Is the voltage divider a good approach to feed the input to the Optoisolator ?

Also, efficiency is an issue as the Arduino (probably a Nano) will be running off batteries.

The target device is a 20V DC motor. I am a novice when it comes to electronics, so I would be grateful of any help or advice you can give.

Many thanks..

Dave.

Is this the best approach ?

Not really, no.

  Is it efficient ?

No, far from it.

  are there any problems I should be aware of ? Precautions I need to take ?

You don't want a voltage divider to power an opto-isolator. An opto-isolator won't be powerful enough to cope with the motor current. You need flyback protection.

  Is the voltage divider a good approach to feed the input to the Optoisolator ?

No, definitely not.

Unless you require galvanic isolation all you need is a simple NPN transistor or N-channel MOSFET circuit:

simulate this circuit – Schematic created using CircuitLab


What's the smallest Arduino board with wifi capabilities? The Photon from Spark IO looks super small. Are there smaller wifi enabled microcontrollers available that can be programmed with the Arduino IDE?

From your question it implies that the Spark IO use the Arduino IDE - it's not. It has two different IDE's, one is web based and the other is downloadable. In addition, it's not an Arduino per-se. It is based on the Wiring library, which is similar to the Arduino library but not exactly the same. And of course the MCU is not Atmel, but that is also the case with Intel's Galileo board.

As to the size question in hand - my believe is that the Arduino products are designed for prototyping, so the size of the product is less important. This is the case for several reasons:

Costs -  the different Arduino products are pretty expensive for mass production.
Peripherals - the Arduino boards come with different peripherals (such as the FTDI chip) which will probably be omitted in an end-user product, and which makes its size larger.
Pins - almost every (official?) Arduino product comes with pre-built male/female header pins, which are excellent for prototyping but not for production, because of the large vertical space they take.

There are many more reasons, but you get the point.

When moving to production with an Internet of Things product, it makes sense to fabricate your own PCB, and design it with a small Atmel chip you used for prototyping (such as ATtiny85) and small Wifi chip, such as the ESP8266. This is an example for such fabricated PCB, although the size is not the 'smallest' possible.

However, for beginners, or a one-time project, it would absolutely make sense to use a pre-fabricated Arduino product, in a small scale that could provide both easy coding capabilities, various libraries and a WiFi included. For that purpose, the Spark IO seems to be at the bleeding edge at the moment - but you never know what will be there tomorrow...


HC-SR04 and LCD Circuit Problem I was designing a circuit that measure distance using HC-SR04 and display it into a LCD.This circuit also have 4 LEDs indicator.But i have a problem.The LEDs doesn't turn on.The LCDs backlight turn on, but it didnt display anything. Btw, i'm using LCD with I2C module.Here is the code:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
#define trigPin 6
#define echoPin 7
int led5cm = 8;
int led7cm = 9;
int led10cm = 10;
int ledoor = 11; //ledoor means LED Out of Range
void setup() { // put your setup code here, to run once: lcd.begin(16,2); lcd.setCursor(0,0);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led5cm, OUTPUT);
  pinMode(led7cm, OUTPUT);
  pinMode(led10cm, OUTPUT);
}
void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;
  if (distance <= 5)
  { lcd.println("Distance < 5 CM");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, HIGH);
    digitalWrite(led7cm, LOW);
    digitalWrite(led10cm, LOW);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  } else if (distance >= 5 || distance <= 7) {
    lcd.println("Distance < 7 CM");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, LOW);
    digitalWrite(led7cm, HIGH);
    digitalWrite(led10cm, LOW);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  }
  else if (distance >= 7 || distance <= 10) {
    lcd.println("Distance < 10 CM");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, LOW);
    digitalWrite(led7cm, LOW);
    digitalWrite(led10cm, HIGH);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  }
  else if (distance > 10) {
    lcd.println("Out of Range");
    lcd.print("Distance = ");
    lcd.print(distance);
    lcd.print(" CM");
    digitalWrite(led5cm, LOW);
    digitalWrite(led7cm, LOW);
    digitalWrite(led10cm, LOW);
    digitalWrite(ledoor, LOW);
    lcd.clear();
    delay(200);
  }
}

Can you please help me solve this problem? Thank you very much!!

To make your LCD work, add code like the following in setup().  (Substitute appropriate values in place of LCDcols and LCDrows, or give them appropriate values via const int ... or enum { ... }; statements.)

  lcd.begin(LCDcols, LCDrows);
  lcd.setBacklightPin(3,POSITIVE); // Might not need this, since info appears to be included in lcd declaration
  lcd.setBacklight(HIGH);
  lcd.clear();          // Clear the display
  lcd.home();

To make the LEDs work better, you may need to change the || connectives in some of the if statements to &&.  An if condition with terms joined by ||, OR, is true if any of its terms are true; with terms joined by &&, AND, all of its terms must be true for the condition to be true.

For example, the condition (distance >= 5 || distance <= 7) is true if distance is 5 or more, or 7 or less; in other words, is always true.