text:
I2C_Anything String / Char Array issues
I've been working with the lovely I2C_Anything.h (thanks to the great work and support from Nick over at http://www.gammon.com.au/forum/?id=10896&reply=9#reply9).. All working great, I was using Serial communication between Teensy 3.1 & mini pro but looking to replace with I2C - I was sending a file name across that was fine, but not managing to figure it out with the I2C_Anything technique.. here's some snippets:
MASTER
const uint8_t MaxMP3Name = 13;
//====================================
// DATA STRUCTURE FOR MP3 SLAVE
//====================================
struct SEND_MP3_STRUCTURE{
  char Filename[MaxMP3Name];
  uint8_t VolLeft;
  uint8_t VolRight;
  uint8_t Command;
};
SEND_MP3_STRUCTURE txMP3;

#define MP3_SLAVE_ADDRESS 77

const uint8_t PlayFile = 1;
const uint8_t PauseFile = 2;
const uint8_t StopFile = 3;

... etc

//#################################//
//##  SEND MP3 COMMAND           ##//
//#################################//
void sendMP3Command(String MP3File, uint8_t Command) {
  char *TextArray[MaxMP3Name];
  MP3File.toCharArray(TextArray, MaxMP3Name);
  txMP3.Filename = TextArray;
  txMP3.VolLeft = VolLeft;
  txMP3.VolRight = VolRight;
  txMP3.Command = Command;
  Wire.beginTransmission(MP3_SLAVE_ADDRESS);
  I2C_writeAnything(txMP3);
  Wire.endTransmission(true);
}

...etc

... not entirely sure what i'm doing, I've tried most variations (using String in the struct vs char *Filename[] and various other attempts).
SLAVE
const uint8_t MaxMP3Name = 13;
//====================================
// RECEIVE DATA FORMAT
//====================================
struct RECEIVE_DATA_STRUCTURE{
  char Filename[MaxMP3Name];
  uint8_t VolLeft;
  uint8_t VolRight;
  uint8_t Command;
};
volatile RECEIVE_DATA_STRUCTURE RXdata;
#define SLAVE_ADDRESS 77
volatile uint8_t newData; // flag to detect I2C activity

// MAKE GLOBAL VERSIONS
String RX_Filename;
uint8_t RX_VolLeft = 30;
uint8_t RX_VolRight = 30;
uint8_t RX_Command = 0;

... etc

//#################################//
//##  MASTER SENDING US DATA     ##//
//#################################//
void onReceiveEvent(int numbytes){
  if(numbytes == 16){
    I2C_readAnything(RXdata);
    newData = 2;
  }
}

... etc

void loop(){
  if (newData==2){// I2C received Data
    RX_Filename = RXdata.Filename;
    RX_VolLeft = RXdata.VolLeft;
    RX_VolRight = RXdata.VolRight;
    RX_Command = RXdata.Command;
    newData = 0; // Clear data sent marker
  }
}

... etc

Hopefully you'll be able to see pretty quickly what i'm trying to do and the method I should be using to do it..
Thanks for any insights
Cheers
Andy

Sorry, still getting used to this comment vs editing questions business, didn't realise it would add my comment when I hit enter so it cut me off... here's full comment:

Hiya Nick, thanks for your suggestion, How you've recommended it is actually how I tried it originally (I don't like using Strings either) - which just ends up giving me the error:
"invalid conversion from 'volatile char*' to 'const char*' [-fpermissive]"
(on the Slave) - obviously the RXdata is updated during the interrupt so can't leave it out (despite the fact it compiles - but doesnt work)..
I got it working soon after I posted by breaking down the filename in the struct to separate chars, then assembling back into char array in a function I made.
That seemed to work fine, but only if I added null char at as the last char (0x00) - I can get the char Filename[MaxMP3Name]; working, but only if I lose the volatile declaration, and it skips the last char.
Thanks for any further help Nick, I really appreciate all you do for the community and I know you're the best guy to help me (not to take anything away from anyone else that wants to jump in ;)
Current solution i'm using that avoids the volatile erros
Obviously could be a for loop etc but I wrote it out this way just to debug and see where the issue was. Not perfect, but breaking it down this way seems to be overcoming the issue of trying to do anything with the volatile variable. (and i've got so much to figure out for so many other parts of the project that I was thinking i'd come back to it later once i'm done with other bits).. Cheers
//#################################//
//##  SEND MP3 COMMAND        ##//
//#################################//
void sendMP3Command(String MP3File, uint8_t Command) {
  char FileName[8];
  MP3File.toCharArray(FileName, MaxMP3Name+1);
  txMP3.File1 = FileName[0];
  txMP3.File2 = FileName[1];
  txMP3.File3 = FileName[2];
  txMP3.File4 = FileName[3];
  txMP3.File5 = FileName[4];
  txMP3.File6 = FileName[5];
  txMP3.File7 = FileName[6];
  txMP3.File8 = FileName[7];
  txMP3.VolLeft = VolLeft;
  txMP3.VolRight = VolRight;
  txMP3.Command = Command;
  StartMicros = micros();
  Wire.beginTransmission(MP3_SLAVE_ADDRESS);
  I2C_writeAnything(txMP3);
  Wire.endTransmission(true);
  EndMicros = micros();
  //Serial.print("MP3 Packet Size: "); Serial.println(sizeof(txMP3));
  //Serial.print("Sending Command To MP3: "); Serial.print(MP3File);Serial.print("   Command; "); Serial.print(txMP3.Command);Serial.print("   Time; "); Serial.print(EndMicros-StartMicros);Serial.println("uS ");
}

... Oh, and on the slave end, I changed the numbytes to be sizeof, but as you say Nick, not even any need for that, i'm not using it on any of my other I2C slaves all running in the project (5 X MCU core system). the filename is then pulled from the I2C array in a siimilar (debugging) way as the master packs them in
//##############################//
// RECONSTRUCT FILENAME
//##############################//
String getFilename(){
  char FileName[] = {
    RXdata.File1,
    RXdata.File2,
    RXdata.File3,
    RXdata.File4,
    RXdata.File5,
    RXdata.File6,
    RXdata.File7,
    RXdata.File8,
    0x00
  };
  return FileName;

}

//#################################//
//##  MASTER REQUESTING DATA     ##//
//#################################//
void onRequestEvent(void){
    I2C_singleWriteAnything(TXdata);
    newData = 1;
}

//#################################//
//##  MASTER SENDING US DATA ##//
//#################################//
void onReceiveEvent(int numbytes){
  if(numbytes == sizeof RXdata){
    I2C_readAnything(RXdata);
    newData = 2;
  }
}

I'm not sure if you are saying you got it working or not, now. if not, can you please post the exact code (edit your question) that is not working?

Hiya Nick, thanks for your help (and continued support to everyone, jeez i see your name just everywhere! lol) - so yeah, i've been off with the fairies in ESP8266 land and only just looked up ;) - in the end i just did a break down of the filename into literally seperate bytes and worked flawlessly ever since. the original issue I think must be teensy 3.1 specific as I've used char arrays all over the place with I2C with no issues, String was my final attempt. i'll post my current 'solution'.

And accept my answer? Or if my answer just pointed you in the right direction, post your own answer and accept it. So long as the question has an accepted, or upvoted, answer. Then the system doesn't nag us. :)

This part looks weird:
void sendMP3Command(String MP3File, uint8_t Command) {
  char *TextArray[MaxMP3Name];
  MP3File.toCharArray(TextArray, MaxMP3Name);
  txMP3.Filename = TextArray;

You have made an array of 13 pointers to strings. This is not what you want. You want the file name to end up into txMP3.Filename.
This would be closer:
void sendMP3Command(String MP3File, uint8_t Command) {
 MP3File.toCharArray(txMP3.Filename, MaxMP3Name);

Personally I wouldn't be using the String class at all, but that should be better.

Now:
void onReceiveEvent(int numbytes){
  if(numbytes == 16){
    I2C_readAnything(RXdata);
    newData = 2;
  }
}

Are you sure it's 16 bytes? What if you change the struct? Let the compiler do the thinking for you:
void onReceiveEvent(int numbytes){
  if(numbytes == sizeof (RXdata)){
    I2C_readAnything(RXdata);
    newData = 2;
  }
}

How you've recommended it is actually how I tried it originally (I don't like using Strings either) - which just ends up giving me the error "invalid conversion from 'volatile char*' to 'const char*' [-fpermissive]" (on the Slave)

This minimal example compiles OK:
#include <Wire.h>
#include <I2C_Anything.h>
const uint8_t MaxMP3Name = 13;
struct RECEIVE_DATA_STRUCTURE{
  char Filename[MaxMP3Name];
  uint8_t VolLeft;
  uint8_t VolRight;
  uint8_t Command;
};

volatile RECEIVE_DATA_STRUCTURE RXdata;
volatile uint8_t newData; // flag to detect I2C activity

void onReceiveEvent(int numbytes){
  if(numbytes == sizeof RXdata){
    I2C_readAnything(RXdata);
    newData = 2;
  }
}

void setup()
{
}

void loop()
{
}

Hiya Nick, thanks for your suggestion, How you've recommended it actually how I tried it originally - which just ends up giving me the error "invalid conversion from 'volatile char*' to 'const char*' [-fpermissive]" (on the Slave)

Sorry, it cut me off, please see my original question as i've added it to it, seems it wont let me add it here as a comment, cheers

You have 5 minutes after making a comment to edit it. Yes, hitting (enter) does commit the comment, but you can edit it.

hmm. it's still not compiling, got the invalid conversion from volatile to  const char error message as above. If I try type casting it I get "call of overloaded 'String(volatile char [13])' is ambiguous" . so something else is causing it to not compile since your minimal example compiles fine. i've got
#include <SPI.h>
#include <Adafruit_VS1053_NanoV3.h>
#include <SD.h>
#include <Wire.h>
#include <I2C_Anything.h>
#include <stdlib.h>
think i'll just use my original fix - breaking struct into separate chars vs array then re-build since it works. thanks again for your efforts, much appreciated

Using String is probably the reason, and I would not use String in an ISR. Since it does dynamic memory allocation you will probably find that the String library does not support re-entrant calls, and thus it will eventually fail.


text:
SD card fails to initialize
I know this question has be asked before on this site. However it was never really answered. I have an Arduino Uno. I am trying to get it to read a 2 GB SDHC Micro SD card. The problem is, the SD card never intializes. I am not sure if there is something wrong with the wiring (which I think is NOT the issue) or the SD card/shield. I have formatted the SD card, but perhaps I did use the wrong settings to do so. Additionally, this SD card is quite old, probably several years. It can still be managed on my PC however.
I bought the following Micro SD shield off Amazon. It has the pins VCC, GND, MISO, CS, MOSI, and SCK, for which I figured the following:
MISO = D0
CS = D1
MOSI = CLK
SCK = D3

I have the circuit wired in the following way:
SCK to Pin 10 on Arduino
CS to Pin 11 on Arduino
MISO to Pin 12 on Arduino
MOSI to Pin 13 on Arduino
VCC to 3.3V source on Arduino
GND to Arduino Ground

The image below is a compilation of the closeup of the shield and my wiring. Not that I am also using Pin 9 in the picture. However this is used for a different portion of the circuit.

The code that I am trying to run comes from the SdFat library. Though the Amazon page says the device can be used without this library, I prefer to have it. I am running the SdInfo.ino example located in SdFat/SdFat/examples/SdInfo/. I have changed the coding so that:
const uint8_t SD_CHIP_SELECT = 10;

I have also tried running the Basic.ino example in the TMRpcm library, located at: TMRpcm/examples/basic, but this doesn't work either. Below is the code:
#include <SD.h>                      // need to include the SD library
//#define SD_ChipSelectPin 53  //example uses hardware SS pin 53 on Mega2560
#define SD_ChipSelectPin 10  //using digital pin 4 on arduino nano 328, can use other pins
#include <TMRpcm.h>           //  also need to include this library...
#include <SPI.h>

TMRpcm tmrpcm;   // create an object for use in this sketch

void setup(){
  tmrpcm.speakerPin = 9; //5,6,11 or 46 on Mega, 9 on Uno, Nano, etc
  Serial.begin(9600);
  if (!SD.begin(SD_ChipSelectPin)) {  // see if the card is present and can be initialized:
    Serial.println("SD fail");
    return;   // don't do anything more if not
  }
  tmrpcm.play("music"); //the sound file "music" will play each time the arduino powers up, or is reset
}

void loop(){
  if(Serial.available()){
    if(Serial.read() == 'p'){ //send the letter p over the serial monitor to start playback
      tmrpcm.play("music");
    }
  }
}

In short. My SD card does not initialize, and I cannot seem to figure out why.

The first thing to try is to use the 'proper' pins for the SPI:
SCK to Pin 10 on Arduino ---> Pin 13
CS to Pin 11 on Arduino ---> Pin 10
MISO to Pin 12 on Arduino ---> Pin 12
MOSI to Pin 13 on Arduino ---> Pin 11
VCC to 3.3V source on Arduino
GND to Arduino Ground

Try that first and see how you get on.

By the way, just thought I'd mention, probably worth just following the Adafruit example word for word as I'm guessing your board is pretty much a good fit for this tutorial:
https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial
good luck getting it rockin' ;)

That breakout board includes a 3.3V regulator and level shifter.  It should be powered from 5V for proper operation.
Also, as @Andology mentions: use the correct SPI pins.

Thanks, I'm at work right now. I'll give it a try later today!

If you have checked everything (wiring, coding your correct pin etc), AND you have already formatted the new card with the correct sd formatter and/or fat32 formatter, and it still does not work; I have found the following worked on some cards:  Simply create an empty (0 bytes) file on the new card.  Cards that were returning all kinds of funny errors (like they are too small - or simply won't initialize)  magically start working !

The solution to this problem, is that you have to let digital Pin 10 as output (for the SD library to work) and put out a logic HIGH by adding “digitalWrite(10,HIGH);”. For Arduino Mega you have to do exactly the same ignore pin 53 completely though the comment asks you to change it to 53.
pinMode(10, OUTPUT); // change this to 53 if you are using arduino mega
digitalWrite(10, HIGH); // Add this line

source: Stack Exchange

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

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

sort: votes


text:
Split arduino run mode depending on active USB connection
Ok, so i have a unit that i want to add information to the EEPROM, using the USB port, such as SSID for wifi shields.
Then i want to disconnect the USB cable, plugin a battery and then it should run its normal loop.
So something like:
IF usb-cable
   run_setup_loop();
ELSE
   run_main_loop();

Which board do you use?

Uno 3 and Nano China

Not really possible with the Uno or Nano. The UNO might work if you change the program on the 16u2 (that does the usb to serial). I think it would be easier to detect serial input (e.g. user presses enter) using if( Serial.available()). And then when some serial data has come in, change "mode" to setup-mode.

The wifi module is serial also so that wouldnt work.

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


text:
Using digital weighing scales with INA125p
Complete electronics beginner here. I'm attempting to build a weighing scale with an Arduino.
I'm attempting to follow this tutorial, with the shield that they use.

I've arranged my load cells on the scale into a Wheatstone Bridge, and I can get some readings just by taking a voltage reading from the two cells marked V+ and V-. The board has terminals that are linked to a INA125p, and the pins should give an amplified reading.
Pin A1:0.96
Pin A2:1.42
Pin A3:5.00
Pin A4:5.00
Pin A5:5.00

Regardless of whether I have the scale wired in or not, I get these readings from the individual pins. The scales seem to be able to take power from the Arduino shield.
The scales that I have are different from the ones in the example. From what I can figure out, the yellow cables that they reference turn their particular scale on when weight is put on it.
I've put the wires where I take the reading into the 2 and 4 terminals on the circuit board that they have (where the tutorial references a differential signal), but again, it makes no change.

unsolder or cut the white wire that is referred to as G3 (Wheatstone bridge mass) on the original printed circuit, extend take it to terminal 1 on the new printed circuit;
unsolder or cut the white wire that is referred to as G2 (Wheatstone
  bridge positive) on the original printed circuit, extend take it to
  terminal 3 on the new printed circuit;
unsolder or cut the white wire that is referred to as G1 and G4 on the
  original printed circuit, extend take it to terminal 4 and 2 on the
  new printed circuit (differential signal on the Wheatstone bridge)

I've attempted lots of different combinations of cables and terminals on the new circuit, but it appears to make no difference to the readings.
My question is:
Based on the tutorial and the drawing above, am I taking the readings from the correct place? Are there any things I'm obviously doing wrong with the circuit itself?
If the circuit is correct, how would I go about trying to get correct readings from the scale when I add weight to it?
I apologise for the vague nature of this question, but I am a complete beginner trying to figure this out, and I am struggling to follow the tutorial. I'll try and provide any additional information that you need.
EDIT - I have a Salter SAL-3003 SSSVDR08 scale.
Each load cell has 3 cables, Red, Black and White. The red ones are the ones marked with the V+, V- etc. On the original board, they were wired in threes.

Re “The scales that I have are different from the ones in the example”, it may help if you edit your question to include the make/model of the scale you got parts from, plus a picture of the load cell and its circuit board connection points

@jwpat7 I've added some information. The original circuit board was wired like this https://goo.gl/photos/epmSuzkkyNKfFSkL7 where R,W,B is red, black and white cables

Wiring 4 three-wire load cells would be done as in http://electronics.stackexchange.com/questions/102164/3-wire-load-cells-and-wheatstone-bridges-from-a-bathroom-scale/199470#199470  Each half-bridge unit would be use as essentially 2 eighths of the cell, with their middle wires corresponding to the non black or white wires in your schematic.  The raw "reading" out of the wheatstone bridge and as an input to the INA125 should be on the order of (5V*0.001 * load/capacity)

See http://arduino.stackexchange.com/a/18698/6628 for some of the load-cell wiring.

Fixed (to some extent)! Faulty connection between the INA125p and the plint it was sitting in. I refitted it and i'm now getting varied readings with the scales, but that's to be expected with the noise the INA125p generates.


text:
Multiple sensor connection help
How would you connect multiple HC-SRO4 ultrasonic sensors to one arduino uno? As of now, I have a bunch of jumper cables, 3 u.s sensors, and one arduino uno board. How would one hook up 3 sensors? A schematic would be excellent!

It depends on what you want to do overall.
Using the HC-SR04 works roughly like this:

you generate a strobe on a pin for a minimum amount of time, and this strobe is understood by the sensor as "emit the ultrasound signal"
then you somehow (more on this later) measure how much time passed between your strobe and a change of level on another pin from the sensor - this is how the sensor notifies you that there was an echo and it has returned.
finally, you convert the time measured into distance, using a conversion algo (typically multiplying by a certain factor) that is specific to the sensor.

Mostly the problem revolves around point #2: how to measure the time elapsed between command (strobe) and answer (change of level).
You have various options, each with pros and cons:

busy looping: it's easy to implement, very straightforward and works right away. The problem is that your arduino will do just that.
polling: it's a less aggressive version of polling, where you check the values every now and then. It lets you do more, but the drawback is that in the worst case the line changes level right after you have checked it, so it will be noticed only at the following iteration. The period used for checking is the maximum error you will get.
GPIO interrupt driven: this is harder but lets your arduino do many other things, while not loosing precision (I'll detail it separately)
HW backed: the AVR on UNO has the ability to capture events: basically there is a timer running that will stop when it gets triggered by a certain event (ex: the change of pin level cause by the echo). It is very precise, but you are limited by the number of HW blocks available on the AVR (3 iirc).

Now about the sub-cases of the GPIO interrupt-driven solution:

EXT based: the ATMega328p present on the UNO has what are called external interrupt sources, which is a fancy way to say that if you configure correctly a pin, the processor will notice when the pin voltage level changes and do something about it (in your case, take a time measurement) - this is quite generic solution, but unfortunately it works only on 2 pins, so you are out of lack with your 3 sensors, unless you implement some scheme where you multiplex 2 or more sensors on only one pin.
Pin-change-interrupt based: on AVR most of the PINS are grouped in ports. Each port contains maximum 8 pins and is labelled with a letter (A, B, C, ..). The way this interrupt works is roughly like the EXT type, but with a catch: you will get an interrupt whenever any of the pins that you have enabled on a certain port will change. In your case you could allocate only one sensor on a certain port, so that it would be obvious that if you get an interrupt for that port, it will be because of that sensor.

So now you can see why I said "it depends". If all you want to do is to get the information about proximity, you can go with busy-looping/polling.
But if you decide later on to do more on the same arduino, be aware that you might have to come back to the implementation of the ultrasonic sensor.
Finally, there is a library for this, but its implementation will fall into one of the cases i mentioned before, so be aware that the same catch applies: at some point you might want to do something that conflicts with the library.
Other points worth mentioning, that you should consider in your design (at least experiment with them):

orientation of the sensors: will they interfere with each other?
timing: do you need/want to activate them all simultaneously or do you prefer to have them activated in sequence?


text:
Why can't I use an optocoupler to drive an AC circuit using the arduino digital pins?
So, when I searched for ways to drive AC circuits from Arduino, everyone suggested relays with a transistor switching circuit to channel an external 5V. I was wondering what would happen if I used an optocoupler like 4n35 to drive an AC circuit. Will the phototransistor inside the chip burn out?

Which AC voltage?

220 V AC mains I meant

Maximum current is 50mA, so not that useful in most cases.

From what you are typing, I guess you are neither an electrician or somehow experienced in this matter. Dealing with mains voltage, in particular building circuitry working with mains voltage requires substantial knowlede to avoid deadly risks as accidental electrocution and fire hazards. In fact in most countries you sail close to the wind doing so without. You face administrative fines up to imprisonment in case of injury to persons. I strongly recommend you fetch some basics about electrical safety and your local regulatory legislation before continuing with what you had in mind.

@Gerben: at least 11 W :) (and the thermal energy of the burning plastic housing).

Thanks for the advice. I want intending to try this. Just needed a theoretical explanation.

Use it with Triac.  I use MOC3020 + BT138 + 330 and 510 Ohm resistors.
It works good as relay and in dimmer scheme.
Scheme is here
http://cyber-place.ru/attachment.php?attachmentid=1030&d=1370462030

No. A 4N35 will switch 150mA at 30V DC. See http://elinux.org/RPi_GPIO_Interface_Circuits for more detail. If you are proposing to switch 110/240V AC there are safety issues. You should look at available commercial modules.

Normally Opto couplers like a 4N35 were not designed to drive an application load.  Typically they are used to trigger another device such as a SCR or Triac.  There is a vidio I would recommend you watch, it gives some information and the comments are good.  Give this a try:
https://www.youtube.com/watch?v=FVef6f2_Si8
Gil

SSR's typically have a arduino friendly 3v + dc input, and can switch 10+ amps of up to 330vac.


text:
Trouble with sleep mode and interrupts
Context
I am building a small battery powered counting device. As with many other projects like this, saving power is critical. I am therefore trying to utilise the sleep mode wherever possible. This is using a 328P as a standalone MCU running on the 1MHz internal clock
The Hall Effect sensor I am using outputs Vcc when nothing is detected, and Ground when something is detected. It therefore seems well suited to being used as a trigger for an interrupt to wake up the 328P from sleep (so that I don't even need to use a watchdog timer.)
Below is an excerpt from my code. This code does put the processor into sleep as desired. However, from testing I have discovered that the device will not sleep when the magnet is left near the sensor, as its output stays LOW. As I only want to detect pulses of a moving piece of metal, this is wasting power. I only want to wake up when it is initially detected on each cycle.
void sleepLoop()
{
  Serial.print("S");

  delay(5);   //scales to 40ms

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  noInterrupts();

  attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, LOW);

  interrupts();
  sleep_cpu();

  //The program will continue from here.

  //First thing to do is disable sleep.
  sleep_disable();
}

I therefore changed
attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, LOW);
to
attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, FALLING);

PROBLEM
Now my processor never goes to sleep. For debugging I have put in a serial print at the start of the loop so that I know it has entered this loop of code. Whether LOW or FALLING is used the 'S' is printed. I only know it is not sleeping because I am measuring the current flow.
I thought the sensor may be going LOW long enough to keep the device awake, but not long enough to register as a count (as I have a debounce in there) so I have checked the output from the sensor with an oscilloscope in case it was momentarily going LOW, but I couldn't see any sign of this.
The findings from the oscilloscope make me feel like there is something about the interrupt function that I am overlooking. Any help would be greatly appreciated!

Could not reproduce. Power usage goes down in both cases and with FALLING I only get a single S printed when signal is low (and sometimes when it goes back high). Are you sure your hall-effect sensor doesn't need a pull-up resistor? What kind of serial output do you get? What is the power-usage (normal, during sleep, during "apparently not sleep")?

Thank you for looking at this :) For me it is very repeatable. Also, I only ever get a single S. It must receive an input before being able to print S again. Datasheet claims 'No External Pull up Resistor Required'. Power usage is ~0.6mA @ 3.6V when awake, and 0.02mA @3.6V when asleep. When in 'not-asleep' its ~0.6mA, hence I believe it is awake

As you didn't have the same problems, I wonder if it is something else I have done.. My full code is here: https://github.com/danjuggles/Sleep-and-counter/blob/master/Arduino_Nano_328P

Looking at the serial output, sleepLoop is never called. So all the code above has nothing to do with the problem.

I just retested this code and I am getting the correct Serial output.. I am underclocking the processor so: Serial.begin(38400);    //Use Baud rate at 4800 on PC (due to 1MHz clock speed)   //  (38400/8)=4800

I know that. No Ss are being printed, so sleepLoop is never called.

Just had a thought. I have my interrupt directly on pin 4 of the 328P, in the Arduino IDE and therefore the code this is called as pin 2, could this be why you aren't seeing the sleep?

Sounds like your sensor may be wired with a pullup resistor - be aware that consumes power when the output is driven low against it.  The hall effect sensor itself may require a few milliamps too, so you might consider a reed switch.

Only low level detect is possible with external interrupt pins (INT0/D2 and INT1/D3) in power down sleep mode. The signal must be low for a number of clock cycles to be detected and the interrupt will detected while the signal is low (and the interrupt is enabled). It is not a transition.
A pin change interrupt could be used instead.
For more details please see chap. 9.5 Power-down Mode and chap. 12. External Interrupts.
Cheers!

There is a more radical alternative, that could yield even higher power savings: use the HAL sensor to trigger a monostable circuit that normally would keep the uC (and the clock source) powered off.
When it starts, get it to update the counter and time the monostable so that it shortly puts the rest of the system back to off.
You can use the eeprom for the counter.
For improved efficiency, get rid of the bootloader and start executing your application right away. If you program from the ISP interface, you do not need the bootloader.

Were filtering contact/range bounce not likely necessary the ATmega counter timer block could probably be configured to count without waking up the processor at all.  But wakeup is not that expensive and has nothing to do with the bootloader as it does not mean the CPU reboots.


text:
Multiple shift registers, 16 bit numbers
Currently working on understanding shift registers and traing to display binary number from 65535 to 0 on a 16 LED's.  Below you can see schematics I am using.

The code I am using is
int latchPin = 8;
int clockPin = 12;
int dataPin = 11;
int numberToDisplay=65535;

void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {

    digitalWrite(latchPin, LOW);

    shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay);

    digitalWrite(latchPin, HIGH);
    delay(500);
  }

void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 16; i++)  {
        if (bitOrder == LSBFIRST)
            digitalWrite(dataPin, !!(val & (1 << i)));
        else
            digitalWrite(dataPin, !!(val & (1 << (15 - i))));

        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}

Problem is when I change numberToDisplay from 0 to 225, everything works and LEDs are lighted correspondingly (if numberToDisplay=225 all red lights are on). But if numbers are bigger than 225 everything just stops working and nothing lights up.
Thank you in advance

Send an array, then you can handle multiple chips. I have examples on my page about the 595 chip.

Your problem is entirely that you declare val to be uint8_t, instead of uint16_t. You are truncating your data to 8 bits before displaying it. One other note, the 74HC595 has a maximum total drive current of 50mA. Your circuit will draw around 90mA for each of the 74HC595's if all of the LEDs are on. You may want to change the resistors to something bigger (510 Ohm, for example) to avoid this problem. Of course that will make the LEDs dimmer, so it's a tradeoff. Here's your project in 123D Circuits. You can simulate it in the browser and look at the code running in the Arduino there.

notice the uint8_t val. You are truncating the 16-bit number back to 8 bit.
One way of fixing this is to split the 16-bit number before calling shiftOut.
shiftOut(dataPin, clockPin, MSBFIRST, highByte(numberToDisplay));
shiftOut(dataPin, clockPin, MSBFIRST, lowByte(numberToDisplay));

Great, havent thought about it. Maybe I could change uint8_t val to byte val in this way there could be any lenght of bits, or it don't work that way?

uint8_t val byte are identical (at least in AVR-C), so that won't help.

I agree with Gerben. But Byte datatype will not help you, since Byte type is an unsigned 8-bit type (the same as uint8_t). Why don't you try this header:
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint16_t val)

Or follow Gerbens idea, just using out of the box shiftOut routine. It shifts 8-bit variables, so you shouldn't need to re-implement the routine.
Regards.


text:
ESP8266 returns whatever is sent through Arduino serial
I am a newbie and working on a kind of WiFi-controlled vehicle (car or maybe hovercraft later). My ESP8266 repeats the commands I send. For example, AT gives AT, AT+GWR gives AT+GWR, dabdabik gives dabdabik, etc.
I am using an Arduino Uno to send commands, as I don't have FTDI related stuff (USB to Serial Converter). I use AA cells for power supply (1.5v*2=3v). I don't even have 3.3 volt direct supply. I am using the Arduino IDE Serial Monitor. I connected the Arduino's TX to the ESP8266's RX via a voltage divider (1.66K Ohm(TX) and 1.66K Ohm (GND)->3.29 Ohm(RX)).
My connections are:
ESP8266----------------Arduino Uno
TX---Voltage divider---RX(d0)
RX---------------------TX(d1)
GND--------------------GND
VCC-------**3V**
CH_PD-----**3V**

Sometimes it gives garbage otherwise it just repeats (weird). Garbage ONLY changes if baud rate is changed.
I flashed it (it seems) with the AT 9.5.2 firmware. Flashing works rarely ONLY with TX to TX connected directly without a voltage divider.
I tried as much as I could after searching the web and ESP8266 forum but still couldn't solve problem.
Please help. I am a student in a small town (Manipal) in Southern India so no good stores nearby and I don't want to buy FTDI or anything online. I am a bit new to electronics, but I am a C++ programmer and student.
UPDATE: I noticed after some resets that it gives full garbage to longer commands most of the time, whereas two-letter commands give partial garbage. For example AT gives IT,TT,OT,etc.
There is no coding.
I am sending the commands directly via Arduino hardware serial pins (rx,tx) and a bare minimum program.

Please amend your question and post your code, since it sounds like a code issue.

I noticed when testing my ESP8266 using the Arduino IDE serial console that ending with a CR repeated what was sent, a NL executed the command and combination of the two yielded a combination of the two behaviours. This could have just been the firmware on mine (it seemed to be non-standard), but it is possible that the behaviour is similar on yours. If you are using CR & NL, it would explain repetition. However, I can't explain commands not executing, or executing abnormally.

When I recieved my first ESP I struggled for weeks trying to get it working. First, the voltage divider is a good thing for its longevity but I got it working without it.
Next about baudrate, mine sent some data at startup on 76800 baud then would work on 9600 baud. You might want to check that out for the garbage you're seeing.
Finally, it might be related to a power draw problem. The ESP has 400mA peaks, this is high for an Arduino and even for a 3.3v USB serial programmer. I had to use a 1A breadboard power supply to actually get it to work. Before buying anything you should try putting a big (220µF or more) capacitor in parallel on the 3.3V power.

AT commands must end with '\r\n'.
'ATE'commands can enable/disable echo. (ATE0: disable, ATE1: enable)
AT commands documentation: http://espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf


text:
Trying to understand Arduino products
Background:
I am new to Arduino world, and I like to buy a board. I am a bit confused how Arduino products are being sold. Coming from Raspberry world, it seems that I don't know what actually Arduino is.
Question:
I am trying to understand what is it that this product offers:

.

Why it says "For Arduino UNO R3"? 2. Isn't it actually an "Arduino UNO R3"? So why it says "For"?
What are MEGA328P and CH340? Does "Arduino UNO R3" comes with other chipsets?

It sounds to me like an Arduino Uno clone.

Why it says "For Arduino UNO R3"?

I would read that as "For Arduino UNO R3 projects" (ie. Uno-compatible).

Isn't it actually an "Arduino UNO R3

No, it's a clone. Or not really a clone (see below) because they used different hardware. It is compatible with the Uno in most respects.

What are MEGA328P?

That is the main chip on the board (actually an Atmega328P).

and CH340?

They have saved money by using a CH340 USB-to-serial chip instead of the Atmega16U2 used on genuine Uno boards. You may need to install a different driver to make that work. I disagree with the other answer(s) that this is a separate board or chip. It is clear from the photo of the chip near the USB socket that it is a CH340 chip there. See, for example https://hackaday.com/tag/ch340/ from which I quote:

The cheapest USB to serial chip on the market appears to be the CH340G, available for 20-40 cents apiece from the usual retailers. There is, however, almost no English documentation, and the datasheet for the CH340 family doesn’t include this chip

They used it because it is cheap.

Does "Arduino UNO R3" comes with other chipsets?

Yes the genuine one comes with an Atmega328P (main processor) and Atmega16U2 (USB interface).

Having said all that, the Uno is a good all-rounder starting board to get going with Arduinos.
Note that they are using the SMD (surface mounted) main processor chip. If you fry it you need to replace the whole board, not just the chip. However the entire board is quite cheap. :)

This was very helpful. Thank you!. One more set of questions and I am good to start :).Is there any good reason I should avoid this type of Colne?  Should I try to find a clone that uses both Atmega328P and Atmega16U2?  This board was sold 222 times all five stars, but I wonder if I should avoid CH340?

@AllanXu The CH340 is ultra-cheap. That tells you most of what you need to know: you get what you pay for.  When it works its fine. Don't expect it to be rugged. There are reports of them being killed very easily by static. The drivers aren't good and have caused problems in the past for people. Avoid it if you use OS X Yosemite or you may end up crippling your whole system. How did they get it so cheap? By cutting corners of course - and that means it's less reliable.

You can't really lose much by trying it at that price. However my experience of a cheap Ethernet board from eBay was that it didn't work nearly as well as the official one.

The board in the picture is not an official Arduino board. It is a clone.  You will note that in the picture the board does not say "Arduino"  It may be 100% compatible or it may not, you have to decide if the low price is worth it.
If you want an official board you should check either http://arduino.cc or http://arduino.org to find official distributors. (see this question for information about why there is both arduino.cc and arduino.org).


text:
How to Create a water screen with solenoid valve in arduino
I want to make a water screen. I will create character with solenoid valve. Sometimes sequential valve will pass to water, sometimes not pass.
And I will create some shape or character.
But I don't know how can I create this character with Arduino.
Do you have any good idea ? Can you help me ?

You can refer to this page for the generic actuation (iow Arduino board + relays shield + power supply for the valves), but that leaves one problem open: timing.
To draw something on a wall of water, you need to make sure that the water flows with a known, constant speed (unless your wall is very tall, I would ignore the effect of gravity, if the initial speed is high enough).
Maybe it can be achieved without this extra step, but to play it safe, I'd also add a pump that feeds all the valves.
This will ensure that you will have a known pressure/speed of the water, thus being able to calculate the timing of the valves.
You can use one of the relays to control also the pump.
Notice also that most likely an arduino UNO/Nano or equivalent will not be sufficient, as you will get relatively few lines.
An ArduinoMega2560 or DUE have far more GPIOs.


text:
LM35 at higher temperatures
I have a question concerning the LM35 sensor: if I'm not too concerned about accuracy (I don't mind having 2 or more degrees off), is it possible to use the LM35 sensor at higher temperatures than the normal range? The project that I'm thinking of using this sensor, temperatures should reach 200 degrees, maximum.
Thanks!

No, you cannot.  The LM35 is rated for an absolute maximum junction temperature of 150°C.  Any higher than that and you will damage it.
For temperatures above that you are better using a thermocouple.

Thank you for your answer. For this project, I want to keep costs low ― so I might try to make my my own thermocouple. I don't know if I will be able to make a good-enough amp at a low cost, though. If anyone else is interested, here are a couple of things that might be useful:
http://hackaday.com/2015/04/06/how-to-build-a-thermocouple-amplifier/ - how to build a thermocouple amp;
https://en.wikipedia.org/wiki/Thermoelectric_effect#Seebeck_effect - the effect that makes it possible to calculate temperature using two different materials;

A thermocouple interface is not expensive on eBay.

Unfortunately I don't live in the US. Compared to the lm35 or thermistors, thermocouple are pretty expensive around here.


text:
Arduino Uno + 12 relays
I'm using a basic relay and I want to use 12 like this. Each one needs 50 milliamps, but the Arduino can supply only 300 milliamps. What can I do?

Use transistors.

You should never drive relays direct from an Arduino.  You always need a driver circuit since each OP pin can only reliably provide up to 25mA.
Every relay needs (at least) an NPN transistor and a flyback diode.  Follow the myriad of examples for controlling one relay on an Arduino and multiply it by 12.
You might like to make things smaller and more manageable by using a paur of ULN2303 chips with 6 darlington drivers in each instead of using 12 discrete transistors.

Im using a transistor for each one. But it still take 50 milli amper. Can you show me a circuit?

@MyNick If you are managing to draw 50mA into the base of a transistor then they must be massive transistors driving house sized relays.   If you are talking about the power supply current draw not the IO pin current draw, then just get a bigger power supply.

Regular transistors that comes from the kit.

@MyNick Then I have to assume (rightly or wrongly, I can't tell since you won't tell me) that you're referring to the power supply current not the IO pin current, in which case - what is your problem? Just use a more powerful power supply for the relays. If you are actually referring to the IO current then god help your Arduino.

This is the circuit for each relay, it takes 50 milli amper from the io pin: https://mail.google.com/mail/u/0/?ui=2&ik=7c60d62fee&view=fimg&th=150943794c75955d&attid=0.1&disp=inline&realattid=1515816904198979584-local0&safe=1&attbid=ANGjdJ9eRNUCnxNPSMue9eI_2SEzxRP7jg00s0ty_jgJJyrD0-eI94xWwlpXSn3q5KYgrIP9QpdxBgSG9mscZxEcG1LzmsNXXF_pkVixDsEDKtTO0iYZkN9fHF6MzoE&ats=1445596069379&rm=150943794c75955d&zw&sz=w1256-h819

@MyNick You know, much as I would love to be able to read your email, I just can't afford the time trying to hack it.

tried to give the link to the image. nvm here you go: http://puu.sh/kUxyk/4a53ce59e5.jpg

I see only 4.3mA, not 50mA.

I just a circuit that a friend drew for me. He told me that the current is not real and i should try to build it and check it. (he just put random values or something). I built it and it took 50 ma (i checked it using multi meter)

WHERE did it take 50mA? At what point in the circuit?

between the io and the resistor into the base of the transistor.

In that case there is something very wrong with your circuit. Given a typical Hfe of 100 you would then expect the transistor to be passing around 5A.  It would literally be on fire.

i found that circuit example : https://www.flickr.com/photos/anachrocomputer/3242387876/in/pool-make
how does the resistor makes a different? if i use 300 ohm what will happen?

@MyNick Yes, that is the normal basic relay driving circuit.

and if i use 300ohm resistor and not 1k?

Then you raise the current allowed through the base, and thus the maximum through the colletcor.  300Ω should be fine, but 1K is better since it limits the maximum that can be drawn from the IO pin.

Ok now i get it, Thank you so much for all of your time


text:
Best way to make an Arduino switch 8 12V LED's
I'm trying to switch multiple 12V LED's with my arduino, based on the input of a (serial-in parallel-out) shift-register.
The 12V comes from a separate battery, so I can use 8 mosfets to get my 12V, and I might even put a parallel-in serial-out shift register in between.
But I'm hoping that there is a cleaner way of doing this.
Is there some kind of component that combines a shift register and a mosfet?
Any ideas on the best way to solve this?

What kind of amperage do these leds use?

The manual that came with my LED lights mentions 90mA per LED.

How about using optocoupler pc817?

ULN2803 FTW, 50v 500mA max, 8 channels, available everywhere, including as boards to plug onto an Arduino

I would recommend using something like the STP08DP05.  ST Microelectronics makes 16 and 24 bit versions as well.  You can also find TI and NXP parts that will do basically the same thing.
With these parts you can hardwire your max current value with a resistor to make sure you don't overdrive the LED.  Just because you can drive the LED at 90mA, doesn't mean you should... it will probably be way to bright.  The IC's can also be daisy-chained to your shift register and you can drive very large strings of LEDs... or use them for RGB LEDs.
Hope that helps!
EDIT - Based on Comments
There are a couple of options.  Note the Vdd represents the voltage supply to the IC itself and the nominal operating voltage is 3.0V up to 5.5V (I'm honestly not sure why they even added 7V as a max value when they specify 5.5V on the next page).
So, Vdd is not necessarily the voltage that your LED's are driven at.  You can drive the LEDs at 12V  (if you need to) and add a series resistor to the OUT pins of the IC's to dissipate the extra heat.
You would probably be fine with 200 ohms per pin.  If you set your current at 20mA, and assuming a 2.2V drop through the LED, that would give you approximately 5.8V at the OUT pins and the IC wouldn't have to dissipate much heat in terms of power.
However, if you don't need to drive them at 12V then I wouldn't bother.  Usually the forward voltage of an LED is 1.8 to 3.3V and you don't need 12V.  However, if you are driving a lot of them then it may be easier to use the 12V.  There are always trade-offs.

That one indeed looks like what I want. I only do no fully understand the schematics. When the max Vdd is 7V. How can I get a Vo of 12V. Or do I have to hookup the OUT pins to the LED cathodes?

I agree with Embedded_Guy. Here's a link to an instructional YouTube video I made for this. It includes a schematic and Arduino code. https://youtu.be/x20uNWz1Res


text:
less expensive alternative arduino board to CMUcam4
Is there any similar (less expensive alternative) arduino board to CMUcam4?
CMUcam4:The CMUcam4 is a fully programmable embedded computer vision sensor. The main processor is the Parallax P8X32A (Propeller Chip) connected to an OmniVision 9665 CMOS camera sensor module.

What's a CMUcam4?

@Majenko www.cmucam.org.

@IgorStoppa I can't click that, and copying and pasting is as onerous as using google to look it up for myself.  My dig was to try and get Rwy5 to provide a link (and even a little information) in the question...

I'm waiting for a bitbake build to complete, so trying to kill time :-)

OpenCV on Raspberry or Beaglebone.

I have used OpenCV on Intel Galileo for doing recognition of sub images from a larger image (given the cover of a magazine, identify it in a pile of magazines partially covering it). The frame rate is far from stellar.
I haven't tried with Edison but it should be much faster, as it's an Atom core vs the pentium-like Quark. OpenCV is optimized for x86.
I used a normal webcam to capture the image, so this solution gives more flexibility in the choice of the sensor.
You could have a look at ROS on Edison.


text:
Problem with structs and pointers(?) - Mega with QueueArray
I'm writing a sketch to run on a Mega that builds up an array of timestamps (using the QueueArray library and DS3231 library). I'm having a problem where a struct I'm defining and then queueing is always referring to the first in the list. The relevant bits of the code looks like this:
#include <QueueArray.h>
#include <DS3231.h>
struct payload_t
{
   unsigned long timestamp;
}

QueueArray <payload_t> dataQueue;
DS3231 clock;
RTCDateTime dt;

void setup() {
   clock.begin();
   clock.setDateTime(__DATE__, __TIME__);
}

void loop() {
    payload_t dataPayload;
    dataPayload.timestamp = getTimestamp();
    dataQueue.enqueue(dataPayload);

    payload_t tempItem = dataQueue.dequeue();

    /**
     * At this stage, the dataPayload.timestamp is correct,
     * but tempItem.timestamp will always show the value from
     * the first item in the queue
     */

    sleep(1000);
}

unsigned long getTimestamp()
{
    RTCDateTime dt = clock.getDateTime();
    return dt.unixtime;
}

As per the comment in the main() loop, the first time a packet is added to the queue, the timestamp matches. For subsequent items, the value retrieved from the queue always gives the timestamp from the first item in the queue.
I feel this is my C knowledge letting me down with something basic, but can anyone point me in the right direction?

Have you got FIFO and LIFO round the wrong way? dequeue() pulls from the front and enqueue() pushes on the back. Also, in your example code, the queue never contains more than one entry; you add a payload, then remove it on the very next line.

I think you have hit the nail on the head. I'm adding to the end of the queue, then grabbing the first item for the comparison check. The first loop iteration will work, but subsequent ones will show a difference. Obvious when you realise! Thanks for the pointer.

I'm confused by the fact that tempItem is always the original stamp - are you definitely using dequeue() in your code, or is if just used here as an example?

It's not your C knowlede letting you down, it's just that you haven't gotten used yet to the weirdness of the arduino ide/compiler.
You do not need to create a main() function.
You need to create a loop() function.
main() is already defined and calls loop() in a loop.
Check any other sketch and you'll notice that it usually defines setup() and loop(), almost never main().
You must put in the setup function all the code that needs to be executed once (settings and initializations) and in the loop() function whatever needs to be executed iteratively.
Also, leave declarations out of loop() unless you want such variables to have scope (and life) limited to only one round of loop()

My mistake - I'd been reading up on C, so wrote main() instead of loop() in the example code. It's definitely loop() in the actual sketch though...

Even with that fix (btw, why didn't you past exactly the code you wrote?) I don't see what is strange with what you describe: you initialize an empty queue, put in one element, then extract that one element right away.
But you do not show how you are reading it. I suggest that you show exactly the code you are using, rather than some modified version of it.
It might well be that the problem lies in how you check that value, rather than in the way it's generated.


text:
Arduino Uno and I2C
How does the arduino uno talk with i2c? i saw the circuit and it use analog input pins but as far as i know you cant use them as output. How does he send data over those pins?

Most pins on the Arduino are multi-function and can be switched into different modes. Analog is just one of those modes. I2C is one of the available modes for the pins that A4 and A5 are connected to.

But i cant change it using pinMode(Output), or can i?

pinMode(OUTPUT) will put the pin into digital IO mode and set it to output - just like every other pin.

but i give it the index of the io pin (to the function), what values i give for the analog pins?

Either the name (A3 for example) or 14 - 19 following on from the highest numbered digital pin D13.

Wow didnt know that, thank you. And then its just a regular output io?

Yep, just like using D0 to D13.

So e.g. pinMode(A3, OUTPUT) and digitalWrite(A3, HIGH).


text:
SoftwareSerial with ESP8266
I am communicating with ESP8266 using SoftwareSerial of Arduino UNO. I can successfully send AT commands and get response when communicating through the terminal. But if i programmatically send particular AT commands there is no response.
For eg:
I type AT in serial monitor I get OK
But if i send the following through SoftwareSerial pins
mySerial.println("AT");

there is no response.
Can anyone tell what will be the solution as to how to send AT commands explicitly.
The sketch is
#include<SoftWareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

void setup() {
// Open serial communications and wait for port to open:
  Serial.begin(9600);
  mySerial.begin(9600);
  mySerial.println("AT");
  delay(100);
  while (mySerial.available()>0 ) {
    char ch=mySerial.read();
    data.concat(ch);
    if(ch=='\n')
      Serial.println(data);
    data="";
  }
}//setup

void loop()  {
  while (mySerial.available()>0 ) {
    char ch=mySerial.read();
    data.concat(ch);
    if(ch=='\n')
      Serial.println(data);
    data="";
  }
  while (Serial.available()>0 ) {
    mySerial.write(Serial.read());
    delay(100);
  }
}//loop

I am using Sparkfun Level Shifter to get 3.3V from 5V. The wiring is straightforward. ESP8266 Vcc and CH_PD to 3.3V; GND to GND; Tx to Arduino 2(Rx) directly; Rx to Sparkfun 3.3V RXO LV side and Arduino 3(Tx) to RXI HV side) so that when Arduino transmits it gets stepped down to 3.3V and ESP8266 receives it. The wiring should be correct as it is working perfectly when AT commands are sent manually.
I tried everything of sending mySerial.write("AT/r/n"), mySerial.print("AT") mySerial.print("\r\n"), etc but nothing seems to work.
Is it that there is some problem with SoftwareSerial. But then how is it working if i send AT commands manually through terminal ?

How is it wired? What pins are you using? Show your sketch.

Can you confirm that you have it wired with the transmit pin on the Arduino going to the receive pin on the ESP8266 and vice versa?

I have been playing with an ESP8266 over the last couple of days with similar results. My conclusion was that it is very timing dependent.
If you build in (fairly large) delays into your code then you will find it works better. The delays are effectively what you are doing as you type in each new command.
I found, for example, that the AT+CWJAP (join access point) command takes quite a while, like 10 seconds or so.
Preferably don't use "actual" delays because they are blocking (unless you don't care about that). You could have a list of commands you want to send, and a system that pulls the next one out of the list when a certain time has elapsed.
If you use something like 5 to 10 second delays between commands you should get better results. At the very least, after sending one command, look for a confirmation string from the device (eg. OK, ERROR etc.).

Thank you for your insight.                                                                        I have done that too. I have added a specific timeout for each command and checked if the software serial has any response after the timeout, but again there is nothing.                                                                                Regarding checking for the response string I did that. For "AT" after a delay of 1sec, I checked if there was any "OK" but again the efforts were in vain. I tried changing the delay. Nothing happened.

Are you sure it is running at 9600? I found mine was configured to run at 115200 baud. I tried changing the delay. Nothing happened. - please amend your question to show the code which incorporates my suggestion.

Same problem here with this code.
Three step for me to make it work :

Use method write() and not println()
Send newline \n when talking to esp8266
don't wait newline to print the response
esp8266Serial.write("AT\n");
delay(100);
while (esp8266Serial.available() > 0 ) {
  char ch = esp8266Serial.read();
  Serial.println(ch);
}

I hope it helps

It appears to me that when the ESP8266 sends a few characters to the Arduino, the initial version of the code always erases those characters (data="";) without ever printing anything to your serial monitor.
So there is no way to tell whether the ESP8266 is sending anything or not.
To make it easier to debug, try printing every character from the ESP8266 to the serial monitor, whether or not it makes a complete message.
What do you see on the serial monitor with the following code?
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

String data = "";

void setup(){
// Open serial communications and wait for port to open:
  Serial.begin(9600);
  mySerial.begin(9600);
  mySerial.println("AT");
}//setup

void loop(){
  if( mySerial.available()>0 ){
    char ch=mySerial.read();
    data.concat(ch);
    Serial.print((int)ch, HEX); // debug: print *every* character, in hex.
    if( ch=='\n' ){
      Serial.println();
      // Use "F()" macro as recommended by
      // https://learn.adafruit.com/memories-of-an-arduino/optimizing-sram .
      Serial.print(F("complete message:"));
      Serial.println(data);
      data="";
      Serial.print(F("waiting for next message ..."));
      }
  }
  if( Serial.available()>0 ){
    mySerial.write(Serial.read());
  }
}//loop

Did you make sure that your lines end with \n\r?
Remember you need both newline characters to send over the line from the terminal.

Did you mean to type "\n\r?" Off hand I can't think of what '\l' would be, but it is late… That said, I would expect the newline ('\n') to be sufficient.

The ESP8266 needs 115200 baud.
The example didn't run clean in my case until I increased the baud rate for the Arduino<->Computer (USB) communication to 115200 baud as well. With 115200 on mySerial and 9600 on USB, an AT request of mine did not return an OK in most cases.

in AT firmware you can set the baud rate. SoftwareSerial can't run at 115200 so must lower baud rate be set for AT firmware


text:
Arduino Wire.onReceive(handler)
It says in the description of the function:

Registers a function to be called when a slave device receives a transmission from a master.

So when does it exactly called? I guess it's not been called for each byte, but its the meaning of receiving transmission from the master. Does it called for each byte? When the master use transmissionBegin? transmissionEnd?

The functions are beginTransmission and endTransmission, not what you had.

It is called at the end of the reception of the entire packet - i.e., when the slave receives the final STOP bit.  It is passed the number of bytes received (which is the number of bytes you requested since I2C has no way of being able to work out if it is actually receiving real data - see here) as the only parameter so you know how many bytes you can then read from the internal buffer without overflowing it.

Yes, so after endTransmission it would be called - once all of the bytes in the buffer have been transferred, or the transfer failed.

It is passed the number of bytes received - on the AVR versions of the library at least, you get the number of bytes you asked for or zero. I have a discussion about this here.

It looks like they fixed it on SAM... I guess the AVR's I2C module isn't as capable as the SAM one and can't work out if it failed to receive or not.

I don't know how they did that, because the slave doesn't control the clock and can't therefore raise a stop condition. The master is clocking out clock pulses, and reading the results. If the slave stops sending the master just receives 1-bits because of the pull-up resistor.

I guess it may never receive an ACK from the slave though after the last byte has been sent by it - so it would time out.

No, it can't be that - when reading the master ACKs the slave, not the slave the master.

I'm not so hot on I2C, preferring the higher speed of SPI. I have, however, found this very very nice PDF that explains it all in detail: http://www.nxp.com/documents/user_manual/UM10204.pdf

From that document: START and STOP conditions are always generated by the master. (P9). - I might set up a test and see if the SAM boards actually handle that, or if they simply didn't test it.

Figure 12 (P15) is pretty much the clincher... there's no way for the master to know if the slave has stopped sending. It just receives "stuff" and blindly fires an ACK back at the slave until it has read its entire quota - when it then sends the stop. I don't see, from that, how they can have actually "fixed" it in the SAM chips.


text:
How to add more inputs on Arduino?
I'm building an instrument that has 72 buttons that can be pressed. Now I'm planning on using Arduino to send data to computer via USB cable about which buttons are pressed. So I figured I'd need 72 different input pins, one for each button(the button is connected to the Arduino via a wire). But, the Arduino doesn't have 72 input pins, so this seems kind of impossible. So what I'm looking for is a way to somehow extend the number of pins on the Arduino or another way to solve my problem. Maybe it would be better to use another micro-controller? Maybe using analog inputs for this is better?
If it makes any difference, the max number of buttons that can be pressed at once is 10.

Look into multiplexing. Create a grid of 8x9 buttons. Energize only one row at a time, and measure all the columns. The energize the next row, and repeat. To reduce the number of pins you could use a shift-register to drive the rows.

There is a whole concept you need to learn:
Matrix
By using a matrix arrangement you can, using (8 + 9 = ) 17 IO pins you can create a grid of 8 × 9 buttons, which is 72 buttons.
This method is used all the time for keypads, and you can read more here: http://playground.arduino.cc/Main/KeypadTutorial
To further reduce the number of IO pins used you can replace the 8 IO pins for one dimension of the matrix with a 3-to-8 decoder, since only one pin is ever active at a time.  That reduces it down to just 12 IO pins for the whole shebang.

Thank you very much! This was very helpful and I'm going to use the concept of matrix to solve my problem.

There are quite a few GPIO expanders available that you could use to increase IO lines in your circuit, mostly running off I2C. Just search "I2C GPIO" on your favorite electronics site/google/ebay
Examples:
https://www.sparkfun.com/products/8130
[No affiliation]
If every sensed key has to be on a GPIO, then this is the way to go.
Having said that, with IO expanders, you will find that sensing large number of keys still takes lots of code on your uC. With some extra software effort, you could eliminate expanders, and rather scan a key matrix as suggested by Majenko

I'm going to stick with key matrix as it seems much easier than any other way. But thanks for suggesting GPIO expanders, I'm sure I'll run out of input pins some day and knowing this beforehand will save me a lot of time.

You may try making something like a button grid, Like the ways Leds are connected in a Led cube, For example - In a 4*4*4 led cube, u don't need 64 pins, but a smart connection of all on x and y axis,
what i mean to say is,
you need to make rows and columns of button, But i don't think this idea would work cause buttons are totally different from leds, But then also try searching for led cube circuit, let it spark a new idea in your mind.


text:
DC motor kickback diode?
I have the following circuit:
And I know it works and that the diode protects the negative voltage from flowing back into the transistor. This is essentially the circuit:
Could someone illustrate what happens when the motor stops? The current normally flows from 5V to GND (and the electrons from GND to 5V, but this doesn't matter (I think?)), and then it reverses when you switch it off, so current comes out of the top of M1, and then what? I don't get it here.

This may not be the best suited for Arduino, it's more about Electronics..

While the motor is being powered the current flows from Vcc to GND as in this circuit:

When the power is disconnected (such as the transistor in the ground connection in your circuit is switched off) amongst other things (including the collapsing of magnetic fields) the spinning of the motor turns it into a generator.  The power generated is the opposite of what was being provided to make it move.  As the magnetic field of the coils collapses additional high voltages are also generated.
When disconnected the motor can be represented as a battery connected backwards.  In that configuration the current flows from the + of this hypothetical battery through the diode into the - thus stopping any current from going elsewhere, as in this circuit:

If it was only the motor turning into a generator, most transistors could cope with that, because the voltage generated by an open generator is limited. The residual current in the motor coils is the problem, because they provide a infinite voltage in theory when interrupted: U=L*dI/dt. In reality this voltage can reach some kV before it breaks down by some means.

@Ariser One thing at a time for the poor learner's brain.

Thank you. This makes a bit more sense now. I was wondering why current wouldn't flow into the arduino but it is shut down so it will obviously find the shortest way which is into the motor. Your representation of the motor as a battery helped me understand it. Thank you!


text:
How to use Infra Red (IR) to reset arduino board
I am a big noob I know that
but can this code be used to reset arduino board (instead of pressing the usual reset button on the board)
I want to reset the board as If am pressing the reset button using IR
int receiverpin = 2; // pin 1 of IR receiver to Arduino digital pin 2
#include <IRremote.h>
IRrecv irrecv(receiverpin); // create instance of irrecv
decode_results results;
void setup()
{
irrecv.enableIRIn(); // start the receiver
}
void(* resetFunc) (void) = 0; //declare reset function @ address 0

void loop()
{
 if (irrecv.decode(&results)) // have we received an IR signal?
{
if(results.value == 0x2FD847B) //if the button press equals the hex
{
  resetFunc();
}
{
irrecv.resume(); // receive the next value
}
}
}

Kind of, yes.  That doesn't actually reset the Arduino, it just sends the program to address 0.
There are two other ways of performing the reset that do a proper full reset:

Enable the watchdog timer and let it time out to reset the CPU.
Connect an IO pin to the RESET pin - keep it in INPUT most of the time but set it to OUTPUT and LOW when you want to reset.

By just jumping to address 0 you aren't resetting the internal peripherals and registers to their reset state, so things like timers and such will still be running when they shouldn't be, etc.  It's better by far to do a real reset instead of just jumping to 0 like that.

i read about both these methods and they won't allow me to reset using IR

@mostafa And what gives you that impression?

well the first one is a pre-set timer right?? no matter what when the timer run out the board will reset I can't see using IR here

@mostafa You only enable the timer when it is time to do the reset. The rest of the time it's disabled so absolutely nothing happens.

oh the second method you want me to connect an IO pin to the reset pin now I get it but won't that contain soldering ????

oh now I get it I will go see it now

@mostafa You only need to solder things if you want to do it permanently - otherwise just stick a wire into the two holes.  For the WDT there is a handy library that does it for you: https://github.com/WickedDevice/SoftReset

A WDT-reset code example


text:
Verifying the timing between relay activations
I would like to verify timings of a relay controlled by an arduino (uno R3). There is a lot going on in the sketch and it does not use the delay function but one which is based on counting milliseconds. The arduino then transmits to another arduino using a radio module (nRF24L01). I'd like to confirm the intervals between the relay, so for instance if the relay is acivated 10 times and there are 5 seconds between each actvation.
So what I was wondering was whether anyone had any reccomendations on methods to verify timings using an external source.
Two ideas I came up with were: have another arduino with a very simple script that measures the timings or try and find/write a verilog script to upload to a mojo fpga and measures the timings.
An ideal situation would be where I have a seperate device that hooks up to the relay and then measures and displays the timings between the relay switches and is extremely precise.
I hope that makes sense, if not please let me know and I'll explain further. Thank you for reading and any help is greatly appriciated.

You could use sigrok with one of the many supported devices.
For example, you can find on ebay an 8 channell 24MHz probe for less than $10.
It's a nice tool to have laying around. For example you can use it as less-invasive-than-serial-print way to detect when internal states of a program change value: just toggle some unused GPIO.

Thank you very much Igor. I've tried pulseview and that seems perfect. I'll go ahead and order a compatable device now. Thanks again


text:
Using TMRpcm library, the audio does not play
I'm using the https://github.com/TMRh20/TMRpcm/wiki library to play wav files from an SD card to a speaker I have attached to my Arduino.
I have run separate tests/programs that ensures:

my speaker is connected properly and can play sound
my SD file is connected properly as it can read and files, text files.

However, I'm trying to use the tmrpcm.play("example.wav") command and nothing is happening. I used wav files that for sure works (from a demo I found online) so it's not the wav file problem.
Anyone have any clue on what is going on and how I can fix this?

This is now 5 months later - but I recently had the same problem.
Because the TMRpcm library plays through pulse width modulation, make sure your speakers are hooked up to a PWM capable pin.
That caused me no end of headaches trying to figure out.


text:
Compilling error not highlighting line in code
A newbe here. How come when I compile with an error I do not get the line or line number highlighted? I Get the errors just can't find where they are.

Because the Arduino "IDE" is a mere toy. If you want real IDE facilities then you need to use a real IDE, not the sub-par text editor that is the Arduino IDE.

I would also recommend to stop relying on that sort of hints. If you read the error message, you will find out that gcc not only tells you where it encounters the error, it also tells you why there is an error.

Update your IDE version to 1.6.x . That should fix your issue.

The line in error can often be highlighted, however because of the way the IDE plays with your source file this is not always the case.
See my post about How the IDE organizes things.
The IDE adds extra lines to your source, and then tries to hide that with #line directives. This can confuse the way error messages are handled. It is another example of the "helpful" IDE not always being helpful.
In any event, as Igor said, you can look for the line number in the error message and use that to find the error. Failing that, look at the quoted source code and search for that.


text:
Arduino communicate between 2 different router in different location
I am on my final year project in I.T. my project is that i want to create a helicopter or quadcopter with a camera attached to it. And i want to control the copter via wifi from an android phone in another location. e.g, the copter is at home and i am somewhere else (work, university etc..). so i wanted to know if i can connect both via 2 different routers and control it and get the live video the camera is actually recording (the idea is to monitor your house when you are away). if that is possible, which arduino hardware will enable me to do that.
Thank you.

It's not the Arduino that has anything to do with this but the routing, port forwarding and/or VPN that you set up between your routers.
I'd have thought, since you're in your final year of IT, you'd at least have some rudimentary knowledge of routing, port forwarding and VPNs...


text:
Sketch upload freezes during write
I'm trying to upload a huge sketch to my Uno R2. It's compiling just fine but it fails to upload at 94% of writing to flash...
The program is so large because of a big array of data in a separate .h file:
#include <avr/pgmspace.h>
const unsigned char PROGMEM data[] = {
  0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f, 0x80, 0x7f, 0x80, 0x7f, 0x80, (etc...)

A test sketch with just 12 bytes of data uploads fine, so the problem is either with the size or some weird bug triggered by some of the data.
Unless i'm missing something, this should technically work.
Command:
    /home/hatagashira/.arduino-1.6.5/hardware/tools/avr/bin/avrdude -C/home/hatagashira/.arduino-1.6.5/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/build8921209068074674980.tmp/program.cpp.hex:i

Output:
avrdude: Version 6.0.1, compiled on Apr 14 2015 at 19:04:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/home/hatagashira/.arduino-1.6.5/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/hatagashira/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         Setting bit clk period        : 5.0
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 3.3
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0
avrdude: reading input file "/tmp/build8921209068074674980.tmp/program.cpp.hex"
avrdude: writing flash (30110 bytes):

Writing | ###############################################    | 94% 5.10savrdude: stk500_recv(): programmer is not responding

To make your question more answerable, first, make up a large example that succeeds in loading, and an example with a hundred more numbers that fails to load; second, edit the question to quote the compiler's size messages [eg, like "Sketch uses 20,112 bytes (65%) of program storage space. Maximum is 30,720 bytes."] for the failing and successful examples.

My two arduino nanos did flash and run the program correctly. I suspect a problem with the uno's serial communication but unwilling to troubleshoot further (i only have one uno). I decided to switch to the nano for further prototyping.


text:
Data exchange through USB Host Shield
I have a Razor IMU, which communicates through a USB to Serial Converter with a USB Host Shield mounted on an Arduino Mega 2560.
Even though serial communication can be achieved directly through the Arduino pins, I'm using a Host shield to keep the pins free for other devices. I found the Host Shield Library, which had specific examples for XBOX and PS3 controllers, Bluetooth devices, keyboards and mice etc., but I can't figure out a way to send/receive data to the IMU connected to the shield.
I'm kind of a noob, so be kind. :)
Thanks!

That really sounds like massive overkill.  You do realise that you have multiple hardware UARTs on the Mega2560?  Also that you can use any pin combination you like using SoftwareSerial to communicate?


text:
Using 2 RGB lights over Bluetooth with a DigiSpark
I'm not that experienced with electronics but I am learning. And I've set a challenge for myself. I have a Digispark USB Development board (and many more but I want to use this one!), I have a Bluetooth module and I have two RGB LEDs which I want to control over the Bluetooth connection. Each LED has to be controlled separately and I want to be able to set each color separately and be able to mix about 256x256x256 colors. Which means, PWM connections. The Bluetooth connection would listen to instructions, receiving four bytes containing RGB values and a value between 0 and three to pick which light needs to be set. (0=None, 1=left, 2=right, 3=both)
Also important is that it needs to be small. It will end up in a container of of roughly 3x3x10 CM in size. (Slightly bigger than 1x1x3 inch.)
The challenge is that Digispark only has 6 pins available so that's not enough to handle this all. I could use three pins and use a 74HC165N Shift Register but that would just turn each color on or off, thus limiting me to 8 colors. That's not good enough! Besides, I also need to connect the four pins of the Bluetooth module.
So my question is simple: What would I need more to build this project? To send the proper six analog signals while having enough pins to handle the Bluetooth datastream?

The function of this device is to display warning signals from a web server nearby. These warning signals are color-coded and relate to two different domains on the server. One light per server. Per server there are about 30 different errors, each with their own admin-defined color. Exact protocols are still under development since I first want to see the device working before I start on the related code. (I'm more a coder anyways.)

Which means, analog connections.

Nope. It means PWM.
How would you control the brightness of a single LED?
By generating a PWM signal with:

sufficiently high frequency to not be able to notice the flickering;
duty cycle proportional to the brightness you want/need, where 100% is full brightness, and 0% is OFF

You only have to do that for each colour of the RGB LED you want to drive.
Ideally you would use a HW block capable of generating the PWM signal, but it can be also bit-banged, should you run out of PWM blocks.
Just keep in mind that different colours have different currents (for the same level of brightness), so you have to pay attention at calculating the correct value of the resistor applied to each colour.
If you prefer to ensure that each channel is driven by a HW PWM generator, you can also use an external driver. Ex: I2C 6-channels PWM generator.

PWM, not analog. Noted. I keep making that mistake. The calculations for the resistors won't be too complex. It doesn't have to be perfect either. The challenge is mostly finding the right part to use and to know how to use that part from the sketch.

To be fair, the Arduino library calls it Analog, but you do get an analog value only after passing through a low pass filter.  I linked what I think is the right part. Did you have a look at it? To know how to program it, you need to check its datasheet. Investing in a  Bus Pirate[1]  might be worth considering, to decouple the I2C programming with the PWM programming.  [1]: http://dangerousprototypes.com/docs/Bus_Pirate

Yes, I checked the part but I can't any distributor in Europe who sells these. Another challenge will be connecting it to my other hardware. Soldering is not my strongest point. Found a shop in my area that sells a Bus Pirate but it takes three weeks before it's back in stock. And that's the most annoying part: waiting for things to become available somewhere.

You can use the extra time practicing soldering ;-)

Well, I'm not in a hurry anyways. :) Plenty of other projects that I want to do first. Most of them coding-related but this project would have been nice to combine coding and electronics. :)


text:
How do I know which is ground and power in Piezo?
I have a piezoelectric sensor. Both pins are the same length. I have one like this: Piezo picture. On the Piezo it's written muRata and 01P. How do I know which do I send to the digital pins and which to the ground? I have an Arduino Uno.

On the one I have, the shorter pin is ground. I discovered that empirically - a scientific word for "I tried it the wrong way round the first time but the magic smoke stayed inside." Afterwards I inspected it more carefully, I found a '+' embossed in the top surface nearer one side. :-o

If you're using just one or sound quality doesn't matter: it doesn't matter.
Otherwise you need to figure it out with a scope like this:

Connect both poles of the connector of the PZT to an oscilloscope (time base approx. 50ms/div, y-axis 200mV/div).
Slightly tap the head of the PZT with your finger. As a result you should get a voltage pulse on the oscilloscope.
Positive Amplitude  -> + pole of the piezo is connected to the inner conductor of the oscilloscope BNC connector.
Negative Amplitude -> + pole of the piezo is connected to the outer conductor of the oscilloscope BNC connector.

Please edit your answer and copy in the (smallish) amount of information from the linked site. StackExchange frowns on link-only answers in case the link goes dead. If you copy the information into your answer it then stands on its own.

@NickGammon Done!


text:
Open the Uart0 Serial Port on Intel Edison
I'll preface this buy saying I am very new to working with Arduino boards or hardware in general.
I am attempting to follow a tutorial on instructables
http://www.instructables.com/id/PCBot/step4/Printer-test/
I have my board and printer wired up properly and I have git cloned the python thermal printer. My issue begins at this paragraph:

Open the UART0 serial port
  by default the GPIO's of the edison are disables.
You can enable them by programming the edison via the Arduino IDE or by using the MRAA library available for several programming languages.
To open enable the UART0 port, TX RX on the edison breakout board, open a Python shell in the thermal and write:
import mraa
x=mraa.Uart(0)

I opened a python shell and entered the import mraa lines and tried to run the printertest.py
I receive an error that says no module named serial. I am not sure where the issue is. I thought the Edison already had python serial installed. I did try to install it with opkg install python-serial but it didn't work. If my issue is with enabling the Uart0 port I am not sure how to go about doing it. I have the Arduino IDE installed but I have no idea how to go about enabling it via the Arduino IDE. The instructions are a bit vague in that paragraph.
*Update I have successfully installed pip and got pyserial installed. Now when I try to run the printertest.py I get an error OSError: [Errno 2] No such file or directory: '/dev/ttyAMA0' which I think is potentially caused by me not succesfully opening Uart0 port but I am not sure how to. I tried adding the import in a shell as well as adding it directly to the code via nano

did you try with pip?

I tried to install pip but I got an error.

I suggest you paste the opkg error. Just as you describe the problem right now, it's hard to say much, without logs. Same as with pip: show how it fails.

I just found out I need unofficial repos to install pip so i'll try that next

I followed this blog to install pip on the edison http://blog.salvius.org/2015/05/installing-pip-on-intel-edison.html ; however, when I try to install pyserial with pip it says -sh: pip: command not found

@IgorStoppa here is the error from just trying to use opkg `root@edison:~# opkg install python-serial
Unknown package 'python-serial'.
Collected errors:

opkg_conf_parse_file: Duplicate src declaration (all http://repo.opkg.net/edison/repo/all). Skipping.
opkg_install_cmd: Cannot install package python-serial.`

how about the full list of repositories? did you check if it's configured as in your example?

Another - painful, for sure - way to install it, is to modify the list of components and rebuild the image. But I'd keep it as really last resort, as it is likely to take easily a couple of hours straight, if not more.

@IgorStoppa I might have to try reflashing the newest image. I don't notice any errors adding official or unofficial repos. The pip installation appears to have no errors.

I have solved the issues and successfully connected this printer with the Compute Module. I solved the issue by changing the target of /dev/ttyAMA0 to /dev/ttyMFD1 as shown by http://iotdk.intel.com/docs/master/mraa/edison.html . This was the final step after I had installed pyserial.


text:
esp8266 garbage out only when using SoftwareSerial
I'm trying to operate the esp8266. When I connect RX+TX pins to pins 1+2 on the Arduino, everything works fine. but when I'm trying to use software serial all hell breaks loose and the recieved data is garbadeged (It seems like everything is ok but I can't read the output data...
more interesting, the output is not consistent!
example:
#include <SoftwareSerial.h>
SoftwareSerial esp8266(11, 10); // RX, TX
void setup() {
    // put your setup code here, to run once:
    esp8266.begin(19200);
    Serial.begin(115200 );
}

void loop() {
    esp8266.write("AT\r\n");
    String buffer;
    Serial.print("SENDING AT...");
    for(uint64_t time = millis();(time+1000) > millis();)
       for(;esp8266.available();buffer+=(char)esp8266.read());
    buffer.replace("\r\n"," ");
    Serial.println("RESPONSE:" + buffer);
}

And the output:

I've tried changing the SerialMonitor baud rate, the input pins, but results are all the same.
I've recently changed the MCU(uno) to a different and even a different esp module from a different supplier,
I am still getting the same results! I can't be the first one to encounter such phenomena...

softwareserial obviously has troubles working at 115kbps, It helped me to pause between the  espSerial.read();    with a delay of 50 to 100...

Try dropping the SoftwareSerial connection speed to 19200. Ie, esp8266.begin(19200). 115200 it is the absolute max the SoftwareSerial can theoretically handle.
Also if you are not using all the change interrupt pins on your MCU (Uno/Nano?) then use any 2 pins from 10, 11, 12 or 13 rather than 3, 2 // RX, TX.
Not sure about sendCommand function. If you just want to test the connection then it should be as simple as:
SoftwareSerial esp8266(10, 11); // RX, TX

void setup() {
    esp8266.begin(19200);
    Serial.begin(115200 );

    char buffer[50];
    esp8266.write("AT\r\n");
    esp8266.readBytes(buffer, sizeof(buffer));
    Serial.println(buffer);

...
}

Obviously once you need to open web pages and recieve responses then you will need a libary to handle IDP+ data. With a bit of coercion I got Adafruit_ESP8266.h working with SoftwareSerial.

This is a good idea. Try using those interrupt pins

Tried all the above, still getting same garbage...

I suspect you may need to change the baud rate of the ESP-8266. It usually defaults to 115200. I used http://neilkolban.com/tech/wiring-up-esp8266s to get started with a terminal emulator and then flashed the latest AT firmware and changed the baud rate to 19200 using AT+UART_DEF=19200,8,1,0,0. Also the update via cloud seemed to work ok for me once I set the AP ssid & pwd. Note it takes a while when using AT+CIUPDATE.

A quick thing to try out.
Try changing Serial.begin(115200); to Serial.begin(9600); and leave  esp8266.begin(115200);.
I'm also completely new to Arduino, but I remember seeing the junk values when the serial monitor baud rate is set to a different value than the Arduino's Baud rate.
I was using Arduino Uno and if I set the baud rate to a value other 9600 in the serial window, I was seeing junk values in println function calls.
i.e Set Serial.Begin(9600); and the Serial Montior baud rate also 9600.

From my experience, if you want to have a consistent data transfer over the softserial, you must disable (in Arduino) the global interrupts for the time of transmission. To disable global interrupts use cli() command, to enable it again use sei() command.

I tried this and didn't improve. No sending worked anymore then...


text:
Problem with connecting ESP8266 to arduino
I have:

Arduino Uno
ESP8266

Problem:
I see SoftAP and can connect to it. But I can't send AT-commands to ESP8266 from Arduino.
I use Arduino app v.1.6.5 for send command to ESP8266 via Arduino. But I don't get answer. And ESP8266 doesn't blinking.
I use this scheme:

Please, help me. I'm trying to fix this is very time consuming.

I had the same problem. I used SoftwareSerial library, so you should set baud rate as 115200 for communication with esp8266. It might look like this:
#include <SoftwareSerial.h>

SoftwareSerial esp8266(2,3);

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

It helped in my case.

I had the same problem. I solved it doing the following:
Connect Arduino TX to a voltage divider (to get 3,3V) and then to TX on ESP8266
Connect Arduino RX to RX on ESP8266
It should work!.
Please read the information on this link
http://rancidbacon.com/files/kiwicon8/ESP8266_WiFi_Module_Quick_Start_Guide_v_1.0.4.pdf

From memory the ESP8266 can pull more current than the Arduino can supply so you need a separate 3.3V supply.
You also need 3.3V/5V logic level shifters on ALL you connections between the Arduino and the ESP, because the ESP of the different in logic levels.

You must need to add another power supply, which will give to the wifi module not just the correct voltage (3v) but the mA that it need.  / other thing you may need to do is connect the ground of Arduino to Ground of the power supply. For me works good.
the connections would be like this

esp TX     > arduino dpin 10
esp RX     > arduino dpin 11
esp CH     > to VCC 3V
esp RST    > to pushbutton connected to gnd
esp GpIO 0 > none
esp GpIO 2 > none
esp VCC > power supply 3v
esp GND > power supply gnd

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

authors: Виталия Александров


text:
Extracting high and low bytes from long
I am learning Arduino from "Arduino cookbook by Michael Margolis", i was reading about bitwise operations and extracting low and high bytes from int. He said that there is no function in Arduino to extract high and low bytes from long at the time of his writing. He stated an alternative to the problem by adding two line of code.
#define highWord(w) ((w) >> 16)
#define lowWord(w) ((w) & 0xffff)

The first line i clearly understood like this, please make corrections if i am wrong.
32bit binary of 16909060 is 0000 0001 0000 0010 0000 0011 0000 0100

by right shifting last 16 bits we will arrive at
32bit binary of 16909060 after right shifting 16bits is 0000 0000 0000 0000 0000 0001 0000 0010

I am not able to interpret the second line.
#define lowWord(w) ((w) & 0xffff)

I would be very grateful if some body explain how the above line of code works?
Thanks.

The second line masks off the top two bytes using a bitwise AND.
When you use a bitwise AND it follows the normal rules for any boolean truth table.  1 & 1 = 1, 1 & 0 = 0...  Since the value is being ANDed, effectively, against 0x0000FFFF, the top two bytes will be cleared to zero while the bottom two bytes are preserved.  In this way you can extract the lower two bytes out of the four byte long.

So  0x0000FFFF is a hexadecimal representation of
0000 0000 0000 0000 1111 1111 1111 1111

Yes.  We use hex because it's much more easily digested when inspected visually. :)  Binary gets really long really fast.

An alternative way of seeing the two operations is through the operators "integer division" and "reminder of the integer division".
In a more generic fashion:
#include <limits.h>
#define highBits(value, number_of_high_bits) \
 (value / (1 << (sizeof(value) * CHAR_BIT - number_of_high_bits)))
#define lowBits(value, number_of_high_bits) \
 (value % (1 << (sizeof(value) * CHAR_BIT - number_of_high_bits)))
This will work regardless the number of bits used for value and with an arbitrary number of high_bits to either keep or shave.


text:
RFduino and HC-05
I am developing a project with RFduino, where I need to connect HC-05 Bluetooth module to my RFduino.
I have tried to find a way to do that, with out luck.
My question: Is it possible to connect HC-05 board to RFduino?
Note: this is my first question at Arduino.stackexchange.com

Connect it to the UART pins and send the right AT commands? What part of it are you struggling with?

in RFduino there is no UART pins, therefore I was wondering if some one has knowledge about RFduino (http://www.rfduino.com/product/rfd22102-rfduino-dip/index.html)

What about pins 0 and 1 - aren't they the uart?

I will try and let you know later, thx for informative feedback so far (pin 0 and 1 are called GPIO 0/AREF and GPIO1

The lack of documentation with those boards is kind of frustrating.  Your best bet is to delve into the actual source code, where you can see in the variant.h file for the board that the "default UART pins" are 0 and 1.  https://github.com/RFduino/RFduino/blob/master/variants/RFduino/variant.h#L133

cool I will work on it right a head. and will come back with feedback

It is btw frusrating. :)


text:
Capacitive sensor MPR121 on Arduino Uno—how many will work?
I need to attach several capacitive sensors MPR121 with each of them using all of its 12 electrodes to an Arduino Uno.
Could you please tell me, how many will work with the voltage and current Arduino Uno supplies?

The answer is 4 regardless of the current consumption.
You can have 4 MPR121 devices on an I2C bus (by connecting the ADDR pin to the right place to select 1 of 4 addresses), and the Uno has one I2C bus - so that means 4 devices.
You could use software I2C to add more devices on other pins, but that's slow and clunky.
But that aside, if you used something to increase the number of I2C buses available, according to the datasheet the peak current consumption is 1mA during sampling, and assuming 300mA maximum for the Arduino's 3.3V regulator, that would mean a maximum of 300 MPR121 connected to the Arduino.  Note that, if you could actually get to the Arduino amongst that tangle of wires, you'd find it getting rather hot...

Thanks very much. So I can use four sensors and in fact 48 electrodes with my Arduino Uno?

Yep. As long as the software you use supports selecting the right bus address.

Uh, I hope so. I wanted to use Sparkfun’s Music Instrument Shield and four of their capacitive sensors.