text:
Ambiguity in Software Serial
HW:
2 Arduino ProMini 16Mhz, 5V
Software serial directly connected using male jumpers on bredboard.
I have creates a software serial port for communication between two arduinos, Parent and child
as per the documentation
http://arduino.cc/en/Reference/SoftwareSerialAvailable
mySerial.available()

should return the number of bytes available in the buffer.
and
mySerial.read();

should give me the byte or return -1 (255) on error.
http://arduino.cc/en/Reference/SoftwareSerialRead
here is my code snippet where i read the values
if(child1.available() > 0){
    Serial.print("ParentReceived Something from child 1\n");
    while(child1.available()){
      recvBuffer1[i] = child1.read();
      Serial.print(recvBuffer1[i], DEC); Serial.print(" ");
      Serial.print(i, DEC); Serial.print(" ");
      i++;
      if(i == FRAME_SIZE) break;
    }
  }

the Serial outputs are for debugging,
The condition for while is true. we go inside.
Now what i receive with child1.read() is the following
ParentReceived Something from child 2
255 0 255 1 255 2 255 3 255 4 255 5 255 6 255 7

all i see is 255.
what i did:
     I first suspected the child of sending these data, but i used a TTL to USB converter to directly read the values being sent by the child and they are received correctly as they should be. even if i TAP the serial ports to another
TTL to USB converter i get 255 on my arduino Serial monitor and the correct data on the sniffer.

You haven't actually asked a question.

Update the question to show the definition of recBuffer1[].  Also include what the child is sending.

Yes, add code where we see the definitions of variables. Also, try bypassing the recvBuffer and directly write the value to the serial window to see if that variable is the issue or not.

Did you call softwareSerial.begin()?

I notice that your code only mentions "child1", but the output you've displayed mentions "child 2". I assume that means you're using more than one instance of SoftwareSerial.
It's important to note that only one instance can receive data at any given time. You need to call listen() on an instance to enable it, which will prevent any other instance from receiving data. (Anything which would have been received by another instance will be discarded.)
See the documentation here: http://www.arduino.cc/en/Reference/SoftwareSerialListen

I would suggest trying this with only one Arduino using Software Serial at first. Try using the receiver board's Hardware Serial to listen, possibly using its Software Serial for the debug output. The Hardware Serial is full duplex - it can talk and listen at the same time. Software Serial is not; only xmit or recv can run at one time, and nothing else on the board runs while it does. That can make synchronizing your two boards difficult if the communication needs to be bi-directional.

The question is - are you "listening"  to the port?
Per doc SoftwareSerial will discard the data if not in"listening state".
The real question is - when not in listening state how does "available" becomes > 0 (true) AKA there is data in SoftwareSerial "buffer"?
It really looks as if there is no real data in the buffer - character count 1 and up to 254 , the buffer content is 255 == -1 which "available" will evaluate as "true".
It can be verified using code to actually get the buffer character count returned from "available" and not just test for if () validity.
if(int count = child1.available())
{
    than print count - how many characters in buffer for real
or

if(child1.available() != -1) to test for real data in buffer.

if(child1.available() > 0){ // anything != 0 will ring true
    Serial.print("ParentReceived Something from child 1\n");
    while(child1.available()){// anything != 0 will ring true
      recvBuffer1[i] = child1.read();
      Serial.print(recvBuffer1[i], DEC); Serial.print(" ");
      Serial.print(i, DEC); Serial.print(" ");
      i++;
      if(i == FRAME_SIZE) break;
    }
  }


text:
arduino nano V3 updated schematics
Does anybody know where to find an updated scematics of Arduino Nano V3? All the Nano drawings I found (even in the Arduino official site) are based on ATMEGA 168 , no one including ATMEGA 328!!!
Thanks
Mike

http://arduino.cc/en/uploads/Main/ArduinoNano30Schematic.pdf

@RogerRowland - The OP is trying to find schematic that shows with an ATMEGA 328 as opposed to the ATMEGA 168 which he stated right in his question.

@MichaelKaras Ahh, sorry, misunderstood and just looked at the V3 bit.

Use the Nano schematic as a reference, and replace the 168 with the 328 from the UNO schematic. The only thing that would change is which pins you're connected to. If you're building this yourself, I'd also steal the hardware reset functionality from the UNO

I think the developers just were lazy, and didn't bother changing the 168 with a 328 in the schematic. Since the pinouts are identical, it doesn't really matter.

the nanov3 zip file is corrupt

this link work:  http://www.electronics-lab.com/make-your-own-arduino-nano-diy-arduino-nano/fswsje2iz6bvkj2/

Go for the manufacturer of this board website i.e. www.gravitech.us. You can get the eagle files and all the data you need. Alternatively, you can download the eagle file of nanov3 directly using this link: http://site.gravitech.us/Arduino/NANO30/ArduinoNano30_Eagle.zip

Also IIRC there's a ground connection that was inadvertently left off the FTDI chip in the published schematics that should be reconnected.

The real issue is that the question is based on an insignificant distinction - no board changes are involved in using a 328p in place of a 168.

source: Stack Exchange

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

sort: votes


text:
Bipolar LEDs flicker when sensors are polled
Or at least that's what I believe is the problem.
I had to add a bipolar LED library to my sketch to get them to work.
As it is now I only have it activated by a specified bit so it can properly drive yellow. Green and Red were working fine (the flickering problem not withstanding) without the bipolar library.
If I have no sensors enabled in the software (java model railroad interface) I'm using with the sketch, then the bipolar LEDs work fine.
The second I add a sensor, then the arduino starts polling the inputs, at which time the bipolar LEDs (all colors) go all wonky. Their flickering coincides with the flickering of the tx/rx lights on the board, so I'm assuming that the polling of the sensors is what is causing it.
Note that the bipolars are the only LEDs attached to another output pin instead of the ground. It's almost like it's polling any pin that's low at the time, which we obviously don't need/want with the pins for the LEDs.
I even changed the order of the sketch which seemed to slightly effect the flickering, but not enough not to be annoying. Keep in mind my level of understanding programming this is at the level of being able to combine sketches...which conflict led us here.
#include <CMRI.h>
#include <CrossingFlasher.h>
#include <BiColorLED.h>

CMRI cmri; // defaults to a SMINI with address 0. SMINI = 24 inputs, 48 outputs
CrossingFlasher crossing(10, 11); // crossbucks
BiColorLED led=BiColorLED(46,47); // (pin 1, pin 2)
BiColorLED led2=BiColorLED(48,49); // (pin 1, pin 2)
BiColorLED led3=BiColorLED(50,51); // (pin 1, pin 2)
BiColorLED led4=BiColorLED(52,53); // (pin 1, pin 2)

void setup() {
  Serial.begin(9600); // make sure this matches your speed set in JMRI
  for (int i=34; i<=53; i++) { pinMode(i, OUTPUT); }
  for (int i=22; i<=33; i++) { pinMode(i, INPUT); digitalWrite(i, HIGH); }
  for (int i=10; i<=11; i++) { pinMode(i, OUTPUT); }
}

void loop() {
  // 1: build up a packet
  cmri.process();

  // 4: update crossing lights. Reads bit 0
  if (cmri.get_bit(0) == true)
    crossing.on();
  else
    crossing.off();

  // 5: update crossing lights
  crossing.update();

  // 6: update Yellow lights. Reads bit 1
  if (cmri.get_bit(1) == true)
    led.setColor(3);
  else
    led.setColor(0);

  led.drive();

  // 7: update Yellow lights. Reads bit 2
  if (cmri.get_bit(2) == true)
    led2.setColor(3);
  else
    led2.setColor(0);

  led.drive();

  // 8: update Yellow lights.
  if (cmri.get_bit(3) == true)
    led3.setColor(3);
  else
    led3.setColor(0);

  led.drive();

  // 9: update Yellow lights.
  if (cmri.get_bit(4) == true)
    led4.setColor(3);
  else
    led4.setColor(0);

  led.drive();

  // 2: update outputs
  digitalWrite(34, cmri.get_bit(5));
  digitalWrite(35, cmri.get_bit(6));
  digitalWrite(36, cmri.get_bit(7));
  digitalWrite(37, cmri.get_bit(8));
  digitalWrite(38, cmri.get_bit(9));
  digitalWrite(39, cmri.get_bit(10));
  digitalWrite(40, cmri.get_bit(11));
  digitalWrite(41, cmri.get_bit(12));
  digitalWrite(42, cmri.get_bit(13));
  digitalWrite(43, cmri.get_bit(14));
  digitalWrite(44, cmri.get_bit(15));
  digitalWrite(45, cmri.get_bit(16));
  digitalWrite(46, cmri.get_bit(17));
  digitalWrite(47, cmri.get_bit(18));
  digitalWrite(48, cmri.get_bit(19));
  digitalWrite(49, cmri.get_bit(20));
  digitalWrite(50, cmri.get_bit(21));
  digitalWrite(51, cmri.get_bit(22));
  digitalWrite(52, cmri.get_bit(23));
  digitalWrite(53, cmri.get_bit(24));

  // 3: update inputs (invert digitalRead due to the pullups)
  cmri.set_bit(0, !digitalRead(22));
  cmri.set_bit(1, !digitalRead(23));
  cmri.set_bit(2, !digitalRead(24));
  cmri.set_bit(3, !digitalRead(25));
  cmri.set_bit(4, !digitalRead(26));
  cmri.set_bit(5, !digitalRead(27));
  cmri.set_bit(6, !digitalRead(28));
  cmri.set_bit(7, !digitalRead(29));
  cmri.set_bit(8, !digitalRead(30));
  cmri.set_bit(9, !digitalRead(31));
  cmri.set_bit(10, !digitalRead(32));
  cmri.set_bit(11, !digitalRead(33));
}

I tried all the suggestions and more, same results.
My uneducated guess is the problem is probably with the CMRI.h library.
Because I FINALLY managed to actually get the native support for yellow in the software I was using (JMRI)
working without any extra bipolar libraries, and guess what? STILL flickers, though this native JMRI
support tends to make it more orange/red in color than the bipolar library did (I prefer the later).
The cmri library is actually attempting to make the arduino emulate another piece of hardware, so for all
I know it might not even be possible to get it to act right.
I've included both cpp and h scripts.
If no one actually figures this out, thanks anyway.
The CMRI.cpp file:
/*
CMRI - a small library for Arduino to interface with the C/MRI
computer control system for model railroads
Copyright (C) 2012 Michael Adams (www.michael.net.nz)
All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "CMRI.h"
#include <Arduino.h>

CMRI::CMRI(unsigned int address, unsigned int input_bits, unsigned int output_bits, Stream &serial_class)
    // store details
: _address(address)
, _rx_length((output_bits + 7) / 8)
, _tx_length((input_bits + 7) / 8)
, _serial(serial_class)

    // set state
, _rx_buffer((char *) malloc(_rx_length))
, _tx_buffer((char *) malloc(_tx_length))

    // parsing state
, _mode(PREAMBLE_1)
, _rx_index(0)

{
    // clear to zero
    for(int i=0; i<_rx_length; i++)
        _rx_buffer[i] = 0;
    for(int i=0; i<_tx_length; i++)
        _tx_buffer[i] = 0;
}

void CMRI::set_address(unsigned int address)
{
    _address = address;
}

// reads in serial data, decodes packets
// automatically responds to POLL requests
// returns packet type so if we got a SET request you know to update your outputs
bool CMRI::process()
{
    while (_serial.available() > 0)
    {
        if (process_char(_serial.read()))
        {
            return true;
        }
    }
    return false;
}

bool CMRI::process_char(char c)
{
    // if it's a SET that's fine do nothing
    // if it's an INIT that's also fine, we don't really care
    // if it's a GET, well, do nothing since it must be someone else replying
    // if it's a POLL then reply straight away with our data
    switch (_decode(c))
    {
        case POLL:
            transmit();
            return true;

        case SET:
            return true;

        default:
            return false;
    }
}

// public methods

bool CMRI::get_bit(int pos)
{
    // 1: divide index by 8 to get byte offset
    char c = get_byte(pos / 8);
    // 2: return bit at that location
    return (bool) ((c >> (pos % 8)) & 0x01);
}

char CMRI::get_byte(int pos)
{
    if (pos > _rx_length)
        return 0; // out of bounds
    else
        return _rx_buffer[pos];
}

bool CMRI::set_bit(int pos, bool bit)
{
    if ((pos + 7) / 8 > _tx_length)
        return false; // out of bounds
    else
    {
        int index = pos / 8;
        _tx_buffer[index] = bit
            ? _tx_buffer[index] | 1 << pos % 8      // if bit=1, then OR it
            : _tx_buffer[index] & ~(1 << pos % 8) // if bit=0, then NAND it
        ;
        return true;
    }
}

bool CMRI::set_byte(int pos, char b)
{
    if (pos > _tx_length)
        return false; // out of bounds
    else
    {
        _tx_buffer[pos] = b;
        return true;
    }
}

void CMRI::transmit()
{
    delay(50); // tiny delay to let things recover
    _serial.write(255);
    _serial.write(255);
    _serial.write(STX);
    _serial.write(65 + _address);
    _serial.write(GET);
    for (int i=0; i<_tx_length; i++)
    {
        if (_tx_buffer[i] == ETX)
            _serial.write(ESC); // escape because this looks like an STX bit (very basic protocol)
        if (_tx_buffer[i] == ESC)
            _serial.write(ESC); // escape because this looks like an escape bit (very basic protocol)
        _serial.write(_tx_buffer[i]);
    }
    _serial.write(ETX);
    _serial.flush();
}

// Private methods
uint8_t CMRI::_decode(uint8_t c)
{
    switch(_mode)
    {
        case PREAMBLE_1:
            _rx_index = 0;
            if (c == 0xFF)
                _mode = PREAMBLE_2;
            break;

        case PREAMBLE_2:
            if (c == 0xFF)
                _mode = PREAMBLE_3;
            else
                _mode = PREAMBLE_1;
            break;

        case PREAMBLE_3:
            if (c == STX)
                _mode = DECODE_ADDR;
            else
                _mode = PREAMBLE_1;
            break;

        case DECODE_ADDR:
            if (c == 'A' + _address)
                _mode = DECODE_CMD;
            else if (c >= 'A')
                _mode = IGNORE_CMD;
            else
                _mode = PREAMBLE_1;
            break;

        case DECODE_CMD:
            if (c == SET)
                _mode = DECODE_DATA;
            else if (c == POLL)
                goto POSTAMBLE_POLL;
            else
                _mode = POSTAMBLE_OTHER;
            break;

        case IGNORE_CMD:
            _mode = IGNORE_DATA;
            break;

        case DECODE_DATA:
            if (c == ESC)
                _mode = DECODE_ESC_DATA;
            else if (c == ETX)
                goto POSTAMBLE_SET;
            else if (_rx_index >= _rx_length)
                { }
            else
                _rx_buffer[_rx_index++] = c;
            break;

        case DECODE_ESC_DATA:
            if (_rx_index >= _rx_length)
                { }
            else
                _rx_buffer[_rx_index++] = c;
            _mode = DECODE_DATA;
            break;

        case IGNORE_DATA:
            if (c == ESC)
                _mode = IGNORE_ESC_DATA;
            else if (c == ETX)
                goto POSTAMBLE_IGNORE;
            break;

        case IGNORE_ESC_DATA:
            _mode = IGNORE_DATA;
            break;

        case POSTAMBLE_OTHER:
            _mode = PREAMBLE_1;
            break;
    }
    return NULL;

POSTAMBLE_SET:
        _mode = PREAMBLE_1;
        return SET;

POSTAMBLE_POLL:
        _mode = PREAMBLE_1;
        return POLL;

POSTAMBLE_IGNORE:
        _mode = PREAMBLE_1;
        return NULL;
}

The CMRI.h file:
    /*
    CMRI - a small library for Arduino to interface with the C/MRI
    computer control system for model railroads
    Copyright (C) 2012 Michael Adams (www.michael.net.nz)
    All rights reserved.

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
    OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
*/

#ifndef CMRI_h
#define CMRI_h

#define _CMRI_VERSION 1.5 // version of this library
#include <Arduino.h>

class CMRI
{
    public:
        CMRI(unsigned int address = 0, unsigned int input_bits = 24, unsigned int output_bits = 48, Stream& serial_class = Serial);
        void set_address(unsigned int address);

        bool process();
        bool process_char(char c);
        void transmit();

        bool get_bit(int n);
        char get_byte(int n);

        bool set_bit(int n, bool b);
        bool set_byte(int n, char b);

        enum {
            MAX  = 258, // max packet length in bytes (64 i/o cards @ 32 bits each + packet type and address bytes)
            INIT = 'I', // PC is telling us stuff we don't really care about
            SET  = 'T', // as in TX from the PC => Arduino, PC is SETing our status
            GET  = 'R', // as in TX from Arduino => PC, PC is GETing our status
            POLL = 'P', // PC wants to know our status
            STX  = 0x02, // start byte
            ETX  = 0x03, // end byte
            ESC  = 0x10, // escape byte
        };

private:
        enum {PREAMBLE_1,PREAMBLE_2,PREAMBLE_3,DECODE_ADDR,DECODE_CMD,DECODE_DATA,DECODE_ESC_DATA,IGNORE_CMD,IGNORE_DATA,IGNORE_ESC_DATA,POSTAMBLE_SET,POSTAMBLE_POLL,POSTAMBLE_OTHER};

        int   _address;
        int   _rx_length;
        int   _tx_length;
        char    _rx_packet_type;
        char* _tx_buffer;
        char* _rx_buffer;

        Stream& _serial;

        // parsing state variables
        int     _mode;
        int     _rx_index;

        uint8_t    _decode(uint8_t c); // process one character received from serial port
};

#endif

The yellow color is make by very quickly alternating between red and green. If you do this fast enough your eyes won't notice. This alternating is done inside led.drive();. If you are polling the sensors, led.drive(); isn't called and the leds aren't alternating for a moment.
Best way would be to use a timer to call led.drive(); every 9ms or less. You could use the timerOne library. I've never used that library, but I think you should use the following code.
#include "TimerOne.h"

...

void setup {
    Timer1.initialize(9000);// call every 9ms
    Timer1.attachInterrupt(callback);

...

void callback()
{
    led.drive();
}

remove all other led.drive calls

Thank you, I will try that. The place I got the bipolar library from did mention the 9ms drive thing, but never actually showed how to do it.

Alternatively you could put a few led.drive() commands in between the digitalWrites and digitalReads at the end of the loop.
I also see your only calling led.drive(). not led2.drive() etc.. The library might not need that, so if it works now, don't change it.

Author of the library here. Sorry for the late reply; hopefully someone else will find this helpful.
Yes, you need to call .drive() on each instance of BiColorLED individually; the library doesn't know about multiple instances. (Thus you need to write led.drive(); led2.drive(); etc.)

The documentation doesn't say how to call .drive() in the right timeframe because it's up to you. My code style tends to rely heavily on cooperative multitasking, where the loop() function calls subroutines that are expected to do a very small amount of work and then return quickly. Thus for me it is sufficient to stick led.drive() right in the main loop() function, as loop() runs quite fast. If you have slower functions you can either attach it to an interrupt with the Timer1 library or the like; or intersperse calls at strategic points inside the slow functions.

You have your LED's across one of the serial I/O lines (Pin 1). Use different pins.

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


text:
SIM300cz AT command returns -1
I connected SIM300cz module's GSM board with Arduino Mega. The GSM board has the pins VCC, GND, RXD, TXD, GND, RI, DTR, STATUS, PWKEY and GND. I connected the GNDs with Arduino's GND, VCC to Arduinos 5V (took power from Arduino), RXD to pin 5, TXD to pin 6 (because of using software serial) and PWKEY to pin 53. My code is as follows:
#include<SoftwareSerial.h>
SoftwareSerial GPRS(5, 6);

int inputPinTempSensor = 0;
float tempCelsius = 0 ;
float thresholdTemp = 45;

void setup()
{
  GPRS.begin(9600);               // the GPRS baud rate
  Serial.begin(9600);  // the Serial port of Arduino baud rate.
  pinMode(53, OUTPUT);
  digitalWrite(53, HIGH);
  delay(100);
}

void loop() {
  GPRS.print("AT+CREG/r");
  Serial.print(GPRS.read());
  delay(2000);
}

The AT command response should be something like "ok" but it's returning -1 for every loop waiting 2 seconds. Why and what could be the solution?
Edit:
Sorry for the mistakes. I was trying different ways with carriage return and new line characters to make it work. Now the code is:
#include<SoftwareSerial.h>
SoftwareSerial GPRS(5, 6);

void setup()
{
  GPRS.begin(9600);               // the GPRS baud rate
  Serial.begin(9600);  // the Serial port of Arduino baud rate.
  pinMode(53, OUTPUT);
  digitalWrite(53, HIGH);
  delay(2000);
  GPRS.println("AT+CREG");
}

void loop() {
  while(GPRS.available()){
    Serial.print(GPRS.read());
  }
}

Now it gives no responses at all. Actually after buying the module I was trying with these examples and they were not working either. So, I thought to test if the AT commands were working properly. I could be a problem with my wiring too.

Did you wire DTR to GND?

Yes, I tried with both keeping it opened and by adding to GND.

BTW, pin 53 is to pull up PWKEY. It's connected to PWKEY.

I think there are 2 mistakes in your code:
First, you should ensure that the 3AT3 commands are termintaed by a new line character:
GPRS.print("AT+CREG/r");

should be changed into:
GPRS.println("AT+CREG/r");

or:
GPRS.print("AT+CREG/r\n");

Nite that I am not sure why you added /r at the end of the AT command, is that supposed to be part of the command? If your intention was to force a new line, then you meant \r not /r, which is not really a new line character but a carriage return (that might be interpreted the same by yur GSM module, but not necessarily).
The the second mistake in your code, is directly calling GPRS.read() without first waiting for a character to be available; in this situation, GPRS.read() will always return -1 as a specific value meaning "no available character to read".
So you should change your code to something like:
// 1st wait for a character to be available
while (!GPRS.available()) {
}
// Then read all available characters and log them to Serial
while (GPRS.available()) {
    Serial.print(GPRS.read());
}

Thanks a lot for your answer. I edited my question. I still have problems.

Note that GPRS.read() will return  -1  if the input buffer is empty.

The correct AT command is AT+CREG?\r. A delay of at least 500ms is also advised after every command, though a timeout loop would be better. Since you didn't send any other commands, the modem will have no further responses for you and the Arduino will return -1 to any Serial.read()s, indicating there's nothing to be read.


text:
Setting timer3 in CTC mode - conflict with servo library
I would like to set up a timer in order to call a function 800 times per second. I'm using the Arduino Mega and Timer3 with a prescaler of 1024. To choose the prescaler factor I've considered the following steps:

CPU freq: 16MHz
Timer resolution: 65536 (16 bits)
Divide CPU freq by the chosen prescaler:
16x10^6/1024=15625
Divide the rest through the desired freq
62500/800=19.
Put the result + 1 in OCR3 register.

I've used the following table to set registers of TCCR3B:

The error
It is impossible to compile the code. This is the error returned by the compiler:

Servo\Servo.cpp.o: In function '__vector_32': C:\Program Files
  (x86)\Arduino\libraries\Servo/Servo.cpp:110: multiple definition of
  '__vector_32' AccelPart1_35.cpp.o:C:\Program Files
  (x86)\Arduino/AccelPart1_35.ino:457: first defined here c:/program
  files
  (x86)/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.3.2/../../../../avr/bin/ld.exe:
  Disabling relaxation: it will not work with multiple definitions

The code
volatile int cont = 0;
unsigned long aCont = 0;
void setup()
{
 [...]
  // initialize Timer3
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3A = 20;
  // turn on CTC mode:
  TCCR3B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3A);
  // enable global interrupts:
  sei();
}

void loop()
{
 // Print every second the number of ISR invoked -> should be 100
 if ( millis() % 1000 == 0)
 {
   Serial.println();
   Serial.print(" tick: ");
   Serial.println(contatore);
   contatore = 0;
 }
}

[...]

// This is the 457-th line
ISR(TIMER3_COMPA_vect)
{
    accRoutine();
    contatore++;
}

void accRoutine()
{
  // reads analog values
}

How to solve the conflict with the servo library?
SOLUTION
Conflict solved using the following code. It compiles but the counter associated with the 800Hz timer doesn't increment its value.
volatile int cont = 0;

void setup()
{
  Serial.begin(9600);
  // Initialize Timer
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3B = 20;
  // turn on CTC mode:
  TCCR3B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();

  Serial.println("Setup completed");
}

void loop()
{
  if (millis() % 1000 == 0)
  {
    Serial.print(" tick: ");
    Serial.println(cont);
    cont = 0;
  }
}

ISR(TIMER3_COMPB_vect)
{
  cont++;
}

Since the main problem has been solved, I've created another question here related to the problem of the counter incrementation.

Do you use the servo library in your progam or not?

Servo.cpp probable does also ISR(TIMER3_COMPA_vect)

@jfpoilpret yes, I'm using motors. I will add the lines in the question. I've read that the servo library uses timer1 on the atmega328.

@jfpoilpret Maybe changing the timer will solve the problem.

Just use Timer1, 4 or 5 instead.

Servo defines interrupt functions for timers 1,3,4 and 5 on megas for COMPA. How about using COMPB?

Haven't tried it yet, I'll do it asap.
How many timers are available considering that I'm using functions like millis(), micros(), servo, serial and i2c communication?

@Gerben Thx, I think I would get the same issue using timer1 since it is used by the servo library as well

You are right. They are just hogging all timers. I guess you have to alter the library slightly by removing the #define _useTimer3 line, or try putting a #undef _useTimer3 right after the include.

@BrettM I've tried with COMPB. It compiles but the timer doesn't work. Should I set te output Compare Register OCR3B to 625 instead of OCR3A?

You will need to load ORC3B instead of ORC3A yes. Also you need to enable the Compare B interrupt in TIMSK3 (change OCIE3A to OCIE3B)

@BrettM Could you please answer the question with the suggestions provided

Unfortunately, The Servo library reserves output compare A (OCR*A) on timers 1,3,4, and 5 when loaded on an arduino mega. Each can only have one ISR, so you will not be able to define your own TIMER*_COMPA_vect while you use Servo without modifying the library.
However, each hardware timer is equipped with 2 output compare registers. Servo does not claim any TIMER*_COMPB_vect interrupts, so those are free to use, and work exactly the same.
You should watch out for the Servo libraries activities, it could change the configuration of your timer. The default order is on megas is 5,1,3,4 and to give each 12 servos. It only configures the timer once it needs it, so you should be fine using timer 3 until you add that 25th servo.
To change your code, use OCR3B instead of OCR3A (the Output Compare Registers) and set bit OCIE3B instead of OCIE3A in TIMSK3 (the Output Compare Interrupt Enable bits). Then you to change your ISR function to  ISR(TIMER3_COMPB_vect){}
CTC mode only works with OCR3A, but if you set TCNT3 to 0 in your interrupt function you can get similar behavior. Remember to remove the line that turns CTC mode on using WGM12.

Ok thanks! Any advice on the incrementation of the counter?


text:
Mac won't detect Serial Port for Leonardo
EDIT: The problem was the cable I was using (see answer below).

I have a MacBook Pro running OS X Yosemite (10.10.1). I connected my Arduino Leonardo to my computer for the first time today (using a Micro USB to USB cable), but my computer isn't detecting it.
When I opened the Arduino IDE I selected Tools > Board > "Arduino Leonardo", but when I try to choose a Serial Port the only options are:

/dev/tty.Bluetooth-Incoming-Port
/dev/cu.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem
/dev/cu.Bluetooth-Modem

I have tried closing and relaunching the Arduino IDE, disconnecting and reconnecting my Arduino Leonardo, and restarting my computer, but I still only see the four Bluetooth ports.
System Information (aka System Profiler) doesn't show anything connected to any of my USB ports.
Thanks in advance!

Have you tried another cable? Another computer?

@IgnacioVazquez-Abrams I don't have any other Micro USB cables, but I tried it with my roomate's PC (Windows 7) and it didn't work there either. Then I realized that the cable I have is only for charging Android phones. It doesn't do any data transfer. I'm going to buy a new cable. Thanks!

I have the same problem but its not cable's fault. I have dual boot with windows and on windows everything works. Any ideas?

@IgnacioVazquez-Abrams's comment made me realize that the problem was the Micro USB cable I was using. It gave the Arduino 5V power from my computer, but didn't support any data connection. I'm buying a new cable.


text:
Assigning values to char array causes program to not run
I have the following code:
#include "LCD12864RSPI.h"
#include "DFrobot_bmp.h"
#include "DFrobot_char.h"

#define AR_SIZE( a ) sizeof( a ) / sizeof( a[0] )
unsigned char wangzhi[]=" www.DFRobot.com ";
unsigned char fused[1024];

void setup()
{
  pinMode(11, OUTPUT);
  for(int i=0;i<4;i++){
  digitalWrite(11,HIGH);
  delay(1000);
  digitalWrite(11,LOW);
  delay(1000);
  }
  LCDA.initDriverPin(2,7,10);
  LCDA.Initialise(); // INIT SCREEN
}
unsigned char* fuse3(unsigned char* a ,unsigned char* b,unsigned char* c){

  int i=0;
  int ac=0;//a counter
  int bc=0; //b counter
  int cc=0;//c counter

  for(int n=0;n<64;n++){
    for(int k=0;k<5;k++){
      fused[i]=a[ac];
       ac++;
       i++;
    }
       for(int k=0;k<5;k++){
        fused[i]=b[bc];
       bc++;
        i++;
    }
        for(int k=0;k<5;k++){
            fused[i]=c[cc];
            cc++;
             i++;
    }
    fused[i]=0x00;
    i++;
  }

  return fused;
}
unsigned char* getMatch(int input){
  input = input & 0x000f;
  switch (input){
   case 0: return g0;
   case 1: return g1;
   case 2: return g2;
   case 3: return g3;
   case 4: return g4;
   case 5: return g5;
   case 6: return g6;
   case 7: return g7;
   case 8: return g8;
   case 9: return g9;
   case 10: return plus;
   case 11: return minus;
   case 12: return times;
   case 13: return g1;
   case 14: return g1;
   case 15: return g1;
   default: return g1;
  }

}
void displayfuse(int number){
// LCDA.DrawFullScreen(fuse3(getMatch(1),getMatch(2),getMatch(3)));
}
void loop(){
  displayfuse(0x1234);

}

This code is a stripped version of the code I need to run to get a bigger project working. But if it somewhat works than the setup should begin by flashing a LED 4 times before continuing. Currently this works. However as you can see I have commented out the line LCDA.DrawFullScreen(fuse3(getMatch(1),getMatch(2),getMatch(3)));. uncommenting this line causes the LED's to flash continuously rather then just 4 times. The library I'm using can be found here. Does anybody know what is going on? To me the first few lines of a program can be affected by a change somewhere this deep inside the code is a form of dark magic.
Weirdly when I change the setup to the following:
void setup()
{
  pinMode(11, OUTPUT);
  for(int i=0;i<15;i++){
  digitalWrite(11,HIGH);
  delay(100);
  digitalWrite(11,LOW);
  delay(100);
  }
  for(int i=0;i<4;i++){
  digitalWrite(11,HIGH);
  delay(1000);
  digitalWrite(11,LOW);
  delay(1000);
  }
  LCDA.initDriverPin(2,7,10);
  LCDA.Initialise(); // INIT SCREEN
}

it stops flashing completely.
Edit having just reuploaded the code again this time the led just remains on all the time.
edit edit
Now with the following code:
#include "LCD12864RSPI.h"
#include "DFrobot_bmp.h"
#include "DFrobot_char.h"

unsigned char fuse[1024];
void setup()
{

  LCDA.initDriverPin(2,7,10);

  LCDA.Initialise(); // INIT SCREEN
  pinMode(11, OUTPUT);
  digitalWrite(11,HIGH);

}
unsigned char* fuse3(unsigned char* a ,unsigned char* b,unsigned char* c){
 unsigned char* fused =(unsigned char*)malloc(sizeof(char)*1024);

  int i=0;
  int ac=0;//a counter
  int bc=0; //b counter
  int cc=0;//c counter

  for(int n=0;n<64;n++){
    for(int k=0;k<5;k++){
      fused[i]=a[ac];
      ac++;
       i++;
    }
        for(int k=0;k<5;k++){
      fused[i]=b[bc];
      bc++;
       i++;
    }
        for(int k=0;k<5;k++){
      fused[i]=c[cc];
      cc++;
       i++;
    }
    fused[i]=0x00;
    i++;
  }
  return fused;
}
unsigned char* getMatch(int input){

  input = input & 0x000f;

  switch (input){
   case 0: return g0;
   case 1: return g1;
   case 2: return g2;
   case 3: return g3;
   case 4: return g4;
   case 5: return g5;
   case 6: return g6;
   case 7: return g7;
   case 8: return g8;
   case 9: return g9;
   case 10: return plus;
   case 11: return minus;
   case 12: return times;
   case 13: return g1;
   case 14: return g1;
   case 15: return g1;
   default: return g1;
  }
}
void displayfuse(int number){
 LCDA.CLEAR();
   delay(100);

 int mask1 = 0xF000;
 int mask2 = 0x0F00;
 int mask3 = 0x00F0;

 int firstnumber = number&mask1>>12;
 int operation = number&mask2>>8;
 int secondnumber= number&mask3>>4;

  LCDA.DrawFullScreen(fuse3(getMatch(firstnumber),getMatch(operation),getMatch(secondnumber)));
  delay(5000);
}
void loop(){
  displayfuse(0x1234);
  delay(1000)
}

This causes the led to not turn on but moving the lines where I make pin 11 output and high one up (beyond the  LCDA.Initialise(); // INIT SCREEN ) then the led will turn on. It can also be turned on by commenting out the       LCDA.DrawFullScreen(fuse3(getMatch(firstnumber),getMatch(operation),getMatch(secondnumber))); line.
Magic is happening...

Short answer: You're out of SRAM.

Memory usage is at around 6 kB leaving quite a bit around.

Are you running this on a Mega?

This is on the "funduino" clone but I have 32 kB avaible and 6 in use.

Is it the Funduino Mega2560?

No the funduino uno

Then the 32kB you have available is flash. You have 2kB of SRAM.

I doubt it; it should complain when you allocate the array space. You did allocate the array space?

Everything in the getMatch(int) function is allocated in a separate header file. The rest happens inside the code I posted.

I was indeed running out of SRAM thank you Ignacio, if you write it into an answer I will accept it.

The 'dark magic' is going to be your program rebooting every time it gets to that line. I would imagine (this isn't a library I know) that you're exceeding an array bound & generating a 'segfault', although it could be that you light up your LCD array & the power draw causes a reboot..
Because the LED flash is at the start of setup, it executes quickly, so generating the appearance of continual flashing when  it re-enters repeatedly.
Your code is going to assign g1[0] when the line in question executes - is g1[] defined to point somewhere valid?

Sounds plausible is there a good way of discovering if a segfault occurred? Normally I would use valgrind but what is the arduino option to check for this?

Headwork ;) Where is the code going when this line executes - see edit.

I'm not sure about it anymore I added in a second flash pattern (flash fast-flash slow) and now it doesn't even begin to flash anymore.

Oh and g[] is defined in a header file as a 320 chars array.

What about g1[]?

Everything in getMatched is well defined all of them are 320 chars arrays.


text:
How to stop Arduino from drawing power through USB
I'm working on an embedded project, where I use arduinos as a "sensor shield" for RaspberryPi (I have model B).
The problem is, that the RaspberryPi's USB port is not powerfull enough to drive WiFi adapter and arduino with sensors. The solution is easy, I will power the sensors externally, not through the RPi.
But I was wondering, is it possible to power whole Arduino externally (through Vin) and use the USB only for serial communication.
To clarify, I know how to solve my problem - use some other mean of communication, than USB - GPIO serial, I2C, wireless, etc... I'm just interested if the whole thing will work, with USB cable which has 5V lead cut, for example.
The main issue I can see with this is, that the USB<->Serial chip is powered through USB only, then it will now work.

Any particular Arduino?

I'm using Nano v3 and Mini, but I'm looking for general solution preferably.

The general solution is to stick to bare MCUs, since each board's power circuitry is slightly different.

If you provide power to the Arduino through Vin this will disconnect USB power through the MOSFET switch.

There are a couple of alternative solutions to the question that I think are worth mentioning.

Use a data only USB cable or manually cut  the VCC and GND wires of the cable.
Remove the USB poly fuse from the arduino board.
Connect external power to one of the input pins to measure the voltage. This measurement can then be used to determine if the external power is connected and is providing sufficient voltage.
If it does the USB power should not be use anyways, otherwise an if statement can be used to disable the code that turns devices that draw power.
USB power will still be used to power the arduino board itself. It also has a limitation in that because the power supply could provide insufficient current it could draw the remaining required current from USB.

Suggestion #1 didn't seem to work for me, which was really confusing.  I'm working with a 3D printer scenario running Marlin on the Arduino.  When I power on the printer/power supply, everything connects like it should when using an unmodified cable.  But, when I try the cable without the VCC & GND wires, nothing will connect.  Could the RAMPS board not be powering the serial bus or something?  Kinda scratching my head on this one.

Only cut VCC and keep ground connected. AFAIR it won‘t work with GND connected

The FTDI chip requires power from the USB side to operate so suggestion 1 will not work

Just cut the VCC line (usually red) in the USB cable.

There are four wires in a USB cable:

Ground
VCC
Data +
Data -

You cannot send data along without a reference ground as you need a potential difference. Hence you must keep the ground connected and just snip the power line (red VCC).

Note that this is not usually necessary as VIN is favoured over USB power.

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


text:
Problem with fading LEDs
I got a breadboard with 10 LEDs, 4 of them fade, to be specific:
3, 5, 6 and 9 are working. 0, 1, 2, 4, 7, 8 are not working.
I'm using LEDs and resistors on all spots, they're all the same. Tried changing things around but the problem doesn't seem to be the resistors or the LEDs.
I'm using the following code (I'll highlight the parts for the fading, by marking it between //** comments).
Does anyone know a way to fix this? Or see any problem?
const int inButton = 13;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;
int delayTime = 100;
int brightness = 0;
int fadeAmount = 5;

void setup() {
  //**
  pinMode(inButton, INPUT);
  for (int out = 0; out < 10; out++){
    pinMode(out, OUTPUT);
  }
  //**

  pinMode(testLed, OUTPUT);
}

void loop() {
  buttonState = digitalRead(inButton);
  if (buttonState != lastButtonState){
    if (buttonState == 1){
      buttonPushCounter++;
    }
  }

  lastButtonState = buttonState;

  if (buttonPushCounter % 5 == 0){
    for (int i = 0; i < 10; i++){
      digitalWrite(i, 1);
      delay(delayTime / 2);
      digitalWrite(i, 0);
    }
  }
  else if (buttonPushCounter % 5 == 1){
    for (int i = 0, j = 9; i < 10, j >= 0; i++, j--){
      digitalWrite (i, 1);
      digitalWrite (j, 1);
      delay(delayTime / 2);
      digitalWrite (i, 0);
      digitalWrite (j, 0);
    }
  }
  else if (buttonPushCounter % 5 == 2){
    for (int i = 0; i < 10; i+=2){
      digitalWrite(i, 1);
    }
    delay(delayTime);
    for (int i = 0; i < 10; i+=2){
      digitalWrite(i, 0);
    }
    delay(delayTime);
    for (int i = 1; i < 10; i+=2){
      digitalWrite(i, 1);
    }
    delay(delayTime);
    for (int i = 1; i < 10; i+=2){
      digitalWrite(i, 0);
    }
  }
  else if (buttonPushCounter % 5 == 3){
    for (int i = 0 ; i < 10 ; i++){
      analogWrite(i, brightness);
    }
    brightness = brightness + fadeAmount;
    if (brightness == 0 || brightness == 255){
      fadeAmount = -fadeAmount;
    }
    delay(25);
  }
  else {
    int R1 = random(10);
    int R2 = random(10);
    int R3 = random(10);
    int R4 = random(10);
    digitalWrite(R1, 1);
    digitalWrite(R2, 1);
    digitalWrite(R3, 1);
    digitalWrite(R4, 1);
    delay(delayTime);
    digitalWrite(R1, 0);
    digitalWrite(R2, 0);
    digitalWrite(R3, 0);
    digitalWrite(R4, 0);
  }
}

Only pins that support PWM support analogWrite() fully. 3, 5, 6, 9, 10, and 11 do. The rest do not.

Ahh, that explains a lot! Is there any way around this, to get them working anyway?

You need to either implement software PWM or use a chip with more PWM channels such as the TLC5940.

Alright, thanks for the help, I'll start looking into that!

To add to @ignacio-vazquez-abrams answer, the pins that support analogWrite() have ~ sign next to their number (on my Uno board they are 9~, 10~, 11~ e.g.);

It's worth noting that this doesn't necessarily apply to 3rd-party clones/derivatives of Arduino boards.


text:
AnalogRead too slow... Faster alternative?
For a program that I'm working on, I want to get an accurate reading from a noisy pressure sensor.  So, the idea that I have is to do a thousand AnalogRead commands on the same port very quickly and then average them.  The pressure readings become very precise, however, the program that I am running becomes very slow.  I need my program to be orders of magnitude faster.
I'm sure that there's a faster way to do AnalogRead commands, especially because I am requesting the same port over and over.  Maybe there's a way that I can take lower resolutions of readings and then average those?  I don't know.  Can anyone help me?  I am an amateur Arduino user looking to learn.
I have done a little bit of research on my own and had trouble finding concrete examples.

And of course you want it on the Due, so my AVR knowledge is little help here. All I can suggest is to crack open the datasheet and learn about the ADC and interrupt facilities on the SAM3X.

Ignacio's proposal is surely a good one if you really need higher sample rates, but I would try another approach:
Average your signal before sampling it! This can be done by connecting a simple RC lowpass to your AD input.
With that you get rid off those high frequency noise you don't need, but without wasting CPU time.

The ADC is rated at up to 15K samples per second.  So reading a 1000 is not a problem.
However, care must be taken in the Vcc used for the ADC (AVcc).  It must be noise free otherwise it will introduce noise into the digital readings, when it actually isn't there in the analogue signal.
See page 256 on the Atmel 328 datasheet for further information.
The RC Lowpass filter should also be used on the AVcc supply, as well as the pressure sensor signal.
I just thought!   Are you using a Serial.print() after each analogRead()???
If so, the serial port will drastically slow down the sample rate.
If this is the case perform a number of analogRead()s then use Serial.print() after some form of processing.

The Due does not use an ATmega chip, and AVcc is already fixed on an Arduino.


text:
Convert Arduino Pro Mini 5v to use 3.3v
Id like to make my 5v pro mini use 3.3 v instead of 5 because i want to use it in an existing piece of electronics that uses 3v throughout.
Looking at the specs for the pro mini it says the 3.3v version can accept higher voltages.
So is there a regulator i can bypass/bridge that will convert my 5v version to a 3.3v version? or am i wasting my time?

Replace U2 with the 3.3V version.

And Q1 with 12mHz (or less) crystal.

Just use 3 diodes in series one diode reduces in 0.7 volts.
5v----->|----->|------->|------- = 2,9volts

I have good news, and I have bad news.
The good news is that only two changes to the board are required to change it from a 5V board to a 3.3V (or any voltage within spec) board.
The bad news is that there's no way in hell you'll be able to do them.
So, we work around them and get the board up and running.
The first is obvious: a 3.3V board should be running off of 3.3V. Since we can't replace the SOT23-5 regulator on the board (the little 5-pin device towards the end) we need a voltage regulator to supply this, directly to the VCC pin. Find yourself a linear or switching regulator that provides this voltage.
The second is that the microcontroller, an Atmel ATmega168/P, is not specced to run at 16MHz when the supply voltage is only 3.3V; the maximum speed is 12MHz. Since we can't replace the crystal on the board (the little silver package next to the MCU itself) we need to perform some trickery to tell the MCU divide the frequency down to something way below safe, and then boost it up after. Use a programmer (see some of my other answers for more info about this) to set the CKDIV8 fuse and then use the routines in avr/power.h in your code to "reduce" the divisor to 2, bringing the clock speed back up to 8MHz. While you're at it, check the BOD fuses to make sure they're not set to something useless like 0b100.
As always, see the datasheet.

wow great. thanks. i may attempt this, but it sounds like it would be easier for me to just get another (3.3v) pro board. theyre cheap and i can use the 5v version some other time.

I'm curious: Why is there no way in hell the OP will be able to do this? It sounds like the 3V3 supply won't be an issue (“because i want to use it in an existing piece of electronics that uses 3v throughout”). Is setting the fuses properly much more difficult than setting up an ArduinoISP and telling your Arduino IDE to write a bootloader for that configuration?

@ChristopherCreutzig: The changes described can be performed by replacing two components on the board. However, even if one had the equipment and skill to replace them it would be a difficult task due to the density of the board. Replacement by someone that doesn't know what's required in the first place? Not happening.

See this nice article by Adafruit, which explains how to run an Arduino Uno at 16Mhz with 3.3v. Both the Arduino Pro Mini and the Uno use the same ATmega328p chip, and they claim that even though running at 16Mhz is out of specs, it should work.
As Ignacio mentioned in his answer, there will be no alternative to downclocking the Mini Pro if you want to play it safe and stay within the specs. If you are willing to take the chance, remove the 5v regulator as suggested, and connect a regulated 3.3v to Vin. Consider the hazards; they might include device resets, misbehaving code or malfunctioning I/O pins.
If you are using an unregulated 3v voltage source, you will need to step up the voltage - using DC DC step up converter such as this one. (By the way - you could also find a step up converter to 5v - hence problem solved...)
In addition, see this SO answer for more details. The safe clock speed for the ATmega328p operating at 3.3v would be 13.33Mhz. For reference, here is the Safe Operating Area graph from the datasheet supplied in the answer:

Again thanks for sharing your knowledge. I may try the step up idea.


text:
Convert long to char array and back
I'm trying to store a state in my data logger. I can read/write fine to SD, but I can't wrap my head around reading/writing a long value correctly - I've build it down to converting it to char array and back.
My best try so far has been
long temp = 1418172669L;
unsigned char buf[4];
buf[0] = temp         & 0xFF;
buf[1] = (temp >>  8) & 0xFF;
buf[2] = (temp >> 16) & 0xFF;
buf[3] = (temp >> 24) & 0xFF;

long  l = buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);

But l is very different from temp - currently the output is -26371. Am I making an obvious mistake?

I suggest using a union:
union {
    char myByte[4];
    long mylong;
} foo;

Char to Long:
Then you can just add the bytes:
foo myUnion;
myUnion.myByte[0] = buf[0];
myUnion.myByte[1] = buf[1];
myUnion.myByte[2] = buf[2];
myUnion.myByte[3] = buf[3];

Then you can access the long as:
myUnion.myLong;

Long to Char:
The same if you want to go the other way from long to char array:
foo myUnion
myUnion.myLong = 1234L;

To access bytes:
myUnion.myByte[0];
myUnion.myByte[1];
myUnion.myByte[2];
myUnion.myByte[3];

Thanks, this worked great (for longs, not for floats). Can you give me a documentation link for union?

@LordT: I don't know why I used float as an example, I must have misread. I have no link to a "documentation" page, but this is a tutorial/example I think is good: http://www.tutorialspoint.com/cprogramming/c_unions.htm

I think the last expression is performed exclusively as an int expression and converted to long only at the end, i.e. before assignment to l.
long  l = buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);

Here the compiler calculates buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24) as an int only.
If you give a hint to the compiler by telling it you want long expressions used, then it should work. The easiest way to do so is to replace the number of bits to be shifted as long literals:
long  l = buf[0] | (buf[1] << 8L) | (buf[2] << 16L) | (buf[3] << 24L);

That should be enough for the compiler to perform the whole operation as long and not loose precision.

Sorry, even with the implicit long, the result is -26371.

Just for completeness, after posting this, I've found another way around it, but @Phataas solution is much more elegant.
Using the ltoa and atol functions, long to char array and vice-verse can be done like this:
char temp[10];
ltoa(669L,temp,10);
long result = atol(temp);

It is also a lot more inefficient.

Yes, it is - but if you're goal is to write a text file to SD card, it beats the binary approach. I've ended up using a combination of the byte conversion with union and the ltoa version for printing to log files


text:
Unable to retrieve heart rate reading and send to JY-MCU Bluetooth
Hello Arduino Community,
I am encountering an issue trying to retrieve a heart rate reading from an op-amp and instrumentation amplifier and sending it via Bluetooth.  I used this website as a basis of my design:  http://www.instructables.com/id/Electrocardiograph-Heart-Rate-Monitor/?ALLSTEPS.  I would appreciate it if you could take a look at that.  Here are a couple of pictures of my design.

Here is the code that I used:
    const int  signal = 7;    // Pin connected to the filtered signal from the circuit
    unsigned long time;
    unsigned long frequency;

    // Internal variables
    int period = 2000;
    int starttime = 2000;
    int input = 0;
    int lastinput = 0;
    unsigned long death = 0;

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

     void loop() {
       delay(1000);

       time = millis();
       input = digitalRead(signal);

       if ((input != lastinput)&&(input == HIGH)) {
       // If the pin state has just changed from low to high (edge detector)
       period = time - starttime; // Compute the time between the previous beat and the one that has just been detected
       starttime = time; // Define the new time reference for the next period computing
       death = time;
      }
      lastinput = input; // Save the current pin state for comparison at the next loop iteration

      if (period < 0) {
      frequency = 0;
      }
      else {
      frequency = 60000/period; // Compute the heart rate in beats per minute (bpm) with the period in milliseconds
      }

      if ((time - death) > 2000) { // Detect if there is no beat after more than 2 seconds
      Serial.println("dead");
      }

      else {
      char freq[3];

      if (frequency/100 == 0) {
       freq[0] = 32; // Print a space to the first character if the frequency is below 100 bpm
      }
      else {
       freq[0] = frequency/100+48; // Sort the hundreds character and convert it in ASCII
      }
       freq[1] = (frequency/10)%10+48; // Sort the thents character and convert it in ASCII
       freq[2] = frequency%10+48; // Sort the units character and convert it in ASCII

      Serial.print(freq);
      Serial.print("alive! ");
      }

      }`

But all I'm getting as output is 'dead'.  I am really starting to lose it here since I am a complete amateur with Arduino and circuitry.  For reference, I copied the design from this image from the website (this is just an enlarged version): http://www.instructables.com/file/FVBC6TYHOW0HQ7H/?size=ORIGINAL.  I would appreciate it if anyone could provide some extra guidance.

This question (at least the wiring) may be better suited for an EE.SE post, it involves circuitry.

As far as I see, you amplified the electr. signal comming from your heart and read the coresponding voltage (hopefully cliped at 5V ;-) ) from pin seven of your arduino. But in your loop you wait for a second then check the pin 7 if it has been changed. This checking lasts a few microseconds so the probabillity that "the heart beats" at that moment is low. It would be better to use interrupts for this purpose to react on every heartbeat. Or at least: avoid any delay where possible. Another finding:  Use if (period <= 0) in your program to avoid divide by zero in the else case.

assuming your circuit works, your code has some serious issues. I rewrote the code for you and also provided a simplified circuit that I have tested and know works.  Instead of getting the pulse from the heartbeat detector circuit, we will simulate it on the Arduino by pulsing pin 2 periodically.
const int  signal = 7;    // Pin connected to the filtered signal from the circuit
unsigned long currentBeatTime;
unsigned long previousBeatTime;

unsigned long frequency;

unsigned long myBeatFreq;
unsigned long myBeat;

// Internal variables
unsigned long period = 0;
int input = 0;
int lastinput = 0;

void setup() {
    pinMode(signal, INPUT);
    pinMode(2, OUTPUT);
    Serial.begin(9600);

    previousBeatTime = millis();
    myBeat = previousBeatTime;
}

void loop() {
    if ( millis()-myBeat > myBeatFreq )
    {
      digitalWrite(2, HIGH);
      myBeat=millis();
    }
    else
    {
      digitalWrite(2, LOW);
    }

    input = digitalRead(signal);

    if ((input != lastinput) && (input == HIGH)) {
        // If the pin state has just changed from low to high (edge detector)
        currentBeatTime = millis();

        period = currentBeatTime - previousBeatTime; // Compute the time between the previous beat and the one that has just been detected
        previousBeatTime = currentBeatTime; // Define the new time reference for the next period computing
    }

    lastinput = input; // Save the current pin state for comparison at the next loop iteration

    // Detect if there is no beat after more than 2 seconds
    if ( (millis() - previousBeatTime) > 2000 )
    {
        Serial.println("dead");
    }
    else
    {
        if (period <= 0)
        {
            frequency = 0;
        }
        else
        {
            frequency = 60000/period; // Compute the heart rate in beats per minute (bpm) with the period in milliseconds
        }

        Serial.print(frequency);
        Serial.println(" : alive! ");
    }
}

It compiles OK!

Hey, sorry, late post.  I'll see if it works for me and get back to you! Thanks!

Hey, I tried it, but it I still received "dead" as my output.  Is there something wrong with my circuitry?

I can't see your images at the moment (blocked from work), but if it says "dead" after two seconds that means signal is never going high. To be sure, connect a wire to pin 7. Start the Arduino and then connect the wire to 5V and then disconnect it repeatedly to simulate a proper heartbeat signal. If it works, you'll know the code is working and something else is wrong with your circuit or the heartbeat detector.

@imjosh Hey I just did that with a battery and found out it still says 'dead'.  I'm pretty sure it's the circuitry, but I don't know how to fix it.

I revised the answer with a circuit I have tested and slightly modified the code.  This should work for you.  To diagnose the rest of the circuit, you should draw a schematic of your circuit and post it to a new question, perhaps on the EE stack exchange.  Pictures of a breadboard are not sufficient and it will help you understand what you've actually done to have to draw it out on paper.


text:
3.5 inch TFT LCD connection diagram with mega r3
Forum post
I would like to ask if someone has this shield fully working.
My biggest problem is the touch screen that i couldn't manage to make it work.
Here is the code i am using:

// ic: ili9327
#define LCD_RD   A0
#define LCD_WR   A1
#define LCD_RS   A2
#define LCD_CS   A3
#define LCD_REST A4

void Lcd_Writ_Bus(char VH)
{
 unsigned char i,temp,data;
 data=VH;
 for(i=8;i<=9;i++)
 {
   temp=(data&0x01);
   if(temp)
     digitalWrite(i,HIGH);
   else
     digitalWrite(i,LOW);
   data=data>>1;
 }
 for(i=2;i<=7;i++)
 {
   temp=(data&0x01);
   if(temp)
     digitalWrite(i,HIGH);
   else
     digitalWrite(i,LOW);
   data=data>>1;
 }

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

void Lcd_Write_Com(char VH)
{
 digitalWrite(LCD_RS,LOW);
 Lcd_Writ_Bus(VH);
}

void Lcd_Write_Data(char VH)
{
 digitalWrite(LCD_RS,HIGH);
 Lcd_Writ_Bus(VH);
}

void Lcd_Write_Com_Data(int com,int dat)
{
 Lcd_Write_Com(com);
 Lcd_Write_Data(dat);
}

void Address_set(unsigned int x1,unsigned int y1,unsigned int x2,unsigned int y2)
{
 Lcd_Write_Com(0x2a); // Set_column_address 4 parameters
 Lcd_Write_Data(x1>>8);
 Lcd_Write_Data(x1);
 Lcd_Write_Data(x2>>8);
 Lcd_Write_Data(x2);

 Lcd_Write_Com(0x2b); // Set_page_address 4 parameters
 Lcd_Write_Data(y1>>8);
 Lcd_Write_Data(y1);
 Lcd_Write_Data(y2>>8);
 Lcd_Write_Data(y2);

 Lcd_Write_Com(0x2c); // Write_memory_start
}

void Lcd_Init(void)
{
 digitalWrite(LCD_REST,HIGH);
 delay(5);
 digitalWrite(LCD_REST,LOW);
 delay(15);
 digitalWrite(LCD_REST,HIGH);
 delay(15);

 digitalWrite(LCD_CS,HIGH);
 digitalWrite(LCD_WR,HIGH);
 digitalWrite(LCD_CS,LOW);  //CS

 Lcd_Write_Com(0xE9);
 Lcd_Write_Data(0x20);

 Lcd_Write_Com(0x11); //Exit Sleep
 delay(100);

 Lcd_Write_Com(0xD1);
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0x71);
 Lcd_Write_Data(0x19);

 Lcd_Write_Com(0xD0);
 Lcd_Write_Data(0x07);
 Lcd_Write_Data(0x01);
 Lcd_Write_Data(0x08);

 Lcd_Write_Com(0x36);
 Lcd_Write_Data(0x48);

 Lcd_Write_Com(0x3A);
 Lcd_Write_Data(0x05);

 Lcd_Write_Com(0xC1);
 Lcd_Write_Data(0x10);
 Lcd_Write_Data(0x10);
 Lcd_Write_Data(0x02);
 Lcd_Write_Data(0x02);

 Lcd_Write_Com(0xC0); //Set Default Gamma
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0x35);
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0x01);
 Lcd_Write_Data(0x02);

 Lcd_Write_Com(0xC5); //Set frame rate
 Lcd_Write_Data(0x04);

 Lcd_Write_Com(0xD2); //power setting
 Lcd_Write_Data(0x01);
 Lcd_Write_Data(0x44);

 Lcd_Write_Com(0xC8); //Set Gamma
 Lcd_Write_Data(0x04);
 Lcd_Write_Data(0x67);
 Lcd_Write_Data(0x35);
 Lcd_Write_Data(0x04);
 Lcd_Write_Data(0x08);
 Lcd_Write_Data(0x06);
 Lcd_Write_Data(0x24);
 Lcd_Write_Data(0x01);
 Lcd_Write_Data(0x37);
 Lcd_Write_Data(0x40);
 Lcd_Write_Data(0x03);
 Lcd_Write_Data(0x10);
 Lcd_Write_Data(0x08);
 Lcd_Write_Data(0x80);
 Lcd_Write_Data(0x00);

 Lcd_Write_Com(0x2A);
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0xeF);

 Lcd_Write_Com(0x2B);
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0x00);
 Lcd_Write_Data(0x01);
 //  Lcd_Write_Data(0x3F);
 Lcd_Write_Data(0x8F); // on internet

 Lcd_Write_Com(0x29); //display on

 Lcd_Write_Com(0x2C); //display on

 digitalWrite(LCD_CS,HIGH);
}

void H_line(unsigned int x, unsigned int y, unsigned int l, unsigned int c)
{
 unsigned int i,j;
 Lcd_Write_Com(0x02c); //write_memory_start
 digitalWrite(LCD_RS,HIGH);
 digitalWrite(LCD_CS,LOW);
 l=l+x;
 Address_set(x,y,l,y);
 j=l*2;
 for(i=1;i<=j;i++)
 {
   Lcd_Write_Data(c);
 }
 digitalWrite(LCD_CS,HIGH);
}

void V_line(unsigned int x, unsigned int y, unsigned int l, unsigned int c)
{
 unsigned int i,j;
 Lcd_Write_Com(0x02c); //write_memory_start
 digitalWrite(LCD_RS,HIGH);
 digitalWrite(LCD_CS,LOW);
 l=l+y;
 Address_set(x,y,x,l);
 j=l*2;
 for(i=1;i<=j;i++)
 {
   Lcd_Write_Data(c);
 }
 digitalWrite(LCD_CS,HIGH);
}

void Rect(unsigned int x,unsigned int y,unsigned int w,unsigned int h,unsigned int c)
{
 H_line(x  , y  , w, c);
 H_line(x  , y+h, w, c);
 V_line(x  , y  , h, c);
 V_line(x+w, y  , h, c);
}

void Rectf(unsigned int x,unsigned int y,unsigned int w,unsigned int h,unsigned int c)
{
 unsigned int i;
 for(i=0;i<h;i++)
 {
   H_line(x  , y  , w, c);
   H_line(x  , y+i, w, c);
 }
}

void LCD_Clear(unsigned int j)
{
 unsigned int i,m;
 Lcd_Write_Com(0x02c); //write_memory_start
 digitalWrite(LCD_RS,HIGH);
 digitalWrite(LCD_CS,LOW);
 Address_set(0,0,479,399);

 for(i=0;i<480;i++)
   for(m=0;m<400;m++)
   {
     Lcd_Write_Data(j);
   }
 digitalWrite(LCD_CS,HIGH);
}

void setup()
{
 for(int p=2;p<10;p++)
 {
   pinMode(p,OUTPUT);
 }
 pinMode(A0,OUTPUT);
 pinMode(A1,OUTPUT);
 pinMode(A2,OUTPUT);
 pinMode(A3,OUTPUT);
 pinMode(A4,OUTPUT);
 digitalWrite(A0, HIGH);
 digitalWrite(A1, HIGH);
 digitalWrite(A2, HIGH);
 digitalWrite(A3, HIGH);
 digitalWrite(A4, HIGH);
 Lcd_Init();
 LCD_Clear(0x00);
}

void loop()
{

 for(int i=0;i<1000;i++)
 {
   Rect(random(300),random(300),random(300),random(300),random(65535)); // rectangle at x, y, with, hight, color
 }
 LCD_Clear(0x00);
}

Here are some pictures:
1 http://imageshack.com/a/img908/7546/YEctM8.jpg
3 http://imageshack.com/a/img537/5378/GIWz2x.jpg
Any suggestions?

Please share some code as well, to help diagnose the problem.

I was able to make mine work, but these screens are all a little different, please post a link to the exact product you have. You don't have any code to read the touch input.

Try to use MCUFriend kbv library I used this library for a 3.5 inch display and the driver on it was ILI9486 this library includes all the function and I have tested the touch also this library works good for it also

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


text:
Driving stepper motors adafruit motor shield v2
I got an Arduino Uno Rev3 and Adafruits Motor Shield V2. I also got two RepRap stepper motors:
Frame size 42 x 42mm - NEMA 17
1.8 degree step angle
Length 47mm
Holding torque 44 N.cm (4.4kg.cm, 62oz.in)
Voltage 2.8V
Current/Phase 1.68A
Resistance/Phase 1.65ohm
Inductance/Phase 2.8mH
Inertia 68g.cm
Bipolar, 4-wire

I thought I was going to be able to run the steppers with the motor shield, but when I tried run one of the steppers it jumps (runs little bit, then stops, then runs etc) until it reach  x steps. I'm driving the the motor shield with 12v 3A power supply.
I read somewhere that the Adafruit steppers should be at-least 5V. Is that correct? Do I need to buy new steppers or any suggestions of stepper driver (shield)?
How many amps do I need to run both steppers at the same time? 1.68 x 2 = 3.36A?
I'm building two of these: https://www.youtube.com/watch?v=C15yPENQ074
Any suggestions/help is appreciated! :)

Adafruit's page says "MOST 1.5-3V MOTORS WILL NOT WORK". https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/powering-motors

Yeah, I did see that... So I need new motors or another shield/controller. Any suggestions? Thanks

That shield is a motor shield; not a stepper shield. You can use it to drive some steppers, but it's not ideal. Regular stepper drivers provide current limiting, micro-stepping etc. PS. by putting 12V on a 2.8v stepper, you can burn out the stepper.


text:
Sniffing RF signals
I am using an Arduino UNO and an RXb6 (I would link to the data sheet if I could find one) to try to decode a RF Signal that controls a remote outlet. I have the devices connected as you would assume 5V+ to 5v, Gnd to Gnd, Antenna is not connected as I think it would only exacerbate my problem, and data is connected to the A0 pin on my UNO.
The problem I am having is with all the noise that I am getting with my signal.I hooked it up to my o-scope to give a better idea of whats happening. When no signal is being transmitted this is the noise I am seeing:

Just lots of static. When I press the remote button I can see a clean signal come through (note that it is cutoff):
I was able to export a CSV of the wave and manually clean it up but it was just such a pain trying to translate it back to highs and lows for the arduino to send.
How can I reduce signal noise on my 433MHz receiver so the arduino can read the actual signal instead of noise?

Put both the transmitter and the receiver in a microwave (or another Faraday cage). Try having the usb lead, that's sticking out, be as short as possible.

Unless you are trying to build something that automatically learns, it will probably be easier to do your analysis with an RTL-SDR dongle, and encode the cleanup up result in an Arduino sketch.

I'm adding another answer, because I don't think the core thing to grasp is mentioned, and others might benefit :)
The noise you are seeing, is actually the result of a feature of the RXB6, KSA6, and similar modules. When they see no signal, they increase gain/sensitivity until they do see a signal. The upside of this is they are very sensitive, and can operate well over quite long ranges. The downside is that if there really is no signal, they will start picking up anything that remotely looks like a signal, the noise you see :)
Dealing with this noise is the job of the software/protocol and other electronics built around the receiver.
A common way to solve it, which the VirtualWire library also uses, is to send some unimportant 'data' first, which makes the receiver decrease it's sensitivity, and then send the  important data.
Another common way is to just repeat the data several times, this is also what your wall sockets most likely do.
In software you can usually find the 'important' parts by looking at pulse lengths, the noise is usually short high pulses, most protocols use far longer pulses, which also have a predictable/defined length.
What I did in exactly your case was to dump the sound recording as a raw signed pcm 16 bit file, which I could then easily read into a bit of software I wrote, which find's the high/low transitions, filters out any short pulses, and then writes out the output (like a csv) you want :)

Dealing with this using audio tools isn't a bad idea.  Readers should not however that the date will be 1-bit samples - it can be expanded to 8 or 16 bit format for compatibility with audio tools, but the raw data from the radio will have only 1 bit.

That is certainly correct :) Nowadays I would use sigrok with a 3$ 'logic analyzer' board :)

noise may be suppressed by squelching the output using a comparator on an AGC threshold level.


text:
How to update a variable in an ISR using Timers
I'm trying to check the frequency of Timer3 using a counter. The value of the counter, declared as volatile, is incremented in the ISR and every second the sum is shown in the main loop and the value reset to zero.
The timer has been set up correctly. (If I choose a 3Hz timer I can see the led blinking)
The problem
The counter isn't incremented. Here is the output:
Setup Completed
tick: 1
tick: 0
tick: 0
tick: 0

CODE
volatile int cont = 0;

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

  pinMode(13, OUTPUT);

  // Initialize Timer
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3B = 20; // 800Hz 5; // 3 Hz
  // turn on CTC mode:
  TCCR3B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();

  Serial.println("Setup completed");
}

void loop()
{
  if (millis() % 1000 == 0)
  {
    Serial.print(" tick: ");
    Serial.println(cont);
    cont = 0;
  }
}

ISR(TIMER3_COMPB_vect)
{
  //digitalWrite(13, digitalRead(13) ^ 1);
  cont++;
}

EDIT
This timer is used to read an anlog value from an accelerometer and store it in an array of float. But at the moment I'm stuck on this update issue.
SOLUTION 1
Thanks to Gerben
volatile int cont = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);

  // Initialize Timer
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3A = 20; // 20; //800Hz 5; // 3 Hz
  // turn on CTC mode:
  TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();
  Serial.println("Setup completed");
}

void loop()
{
  delay(1000);
  Serial.println(cont);
  cont = 0;
}

ISR(TIMER3_COMPB_vect)
{
  cont++;
}

SOLUTION 2
Thanks to BrettM
volatile int cont = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);

  // Initialize Timer
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3B =  20; //800Hz 5; // 3 Hz
  // turn on CTC mode:
  //TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();
  Serial.println("Setup completed");
}

void loop()
{
  Serial.println(cont);
  cont = 0;
  delay(1000);

}

ISR(TIMER3_COMPB_vect)
{
  TCNT3 = 0;
  cont++;
}

And if you uncomment the digitalWrite line you see the LED blink about once per second (every 0.66s)?

Yes, If I uncomment digitalWrite and set OCR3B = 5; the led blinks at approximately that frequency.

Then it's a mistery. Have you tried commenting out the cont = 0; inside the loop? What happens then?

Also, the output you provided doesn't match the code, as each line should be "tick: 0" instead of just "0".

Yes I've updated the text with the output I get. Now there is a 1! XD

Try increasing the frequency. I think your if statement may be clearing the counter more often than the interrupt is called, somehow. But then you should see more ones in the output. Also let if run for longer (say 1 minute) and paste the results. Also, when you update the question, leave the old output so your question makes sense (without the edit history).

I've set OCR3B to 20 (800 Hz, prescaler 1024 -> 800Hz right?) and commented the line cont = 0 in the if statement. The output in the EDIT2

Can't see the EDIT2. Did you really save it?

Yes, I've tried printing the value every 5, 20 and 50 sec. The count's value doesn't change.

I suspect that the interrupt routine is being called only once and then it is disabled. I've read somewhere that the interrupts are disabled when an interrupt code is running, and in some cases you have to re-enable it, but I'm really not sure if that's the case. Hopefully someone more knowledgeable will come to our rescue...

In CTC mode the top is OCR3A, not OCR3B!
After that TIMSK3 |= (1 << OCIE3B); should also be changed to TIMSK3 |= (1 << OCIE3A);, and ISR(TIMER3_COMPB_vect) to ISR(TIMER3_COMPA_vect)
For 3Hz, OCR3A should be 5208, not 20.
Technically TCCR3B |= (1 << WGM12); should be TCCR3B |= (1 << WGM32);

With your configuration the counter is not updated and every second the "Setup completed" sentence, (written in the setup() function!) is shown. Really weird behaviour.

Solved using TIMSK3 |= (1 << OCIE3B);. Thank you Gerben! Please modify your answer and I'll accept it as solution.

I forgot the mention you also need the change the ISR vector. ISR(TIMER3_COMPB_vect) should be ISR(TIMER3_COMPA_vect). If an ISR isn't defined, the AVR will reset itself, like you were experiencing. Glad you got it working.

It seems my answer to this question was previously incomplete, thanks for pointing out that CTC mode only works with OCR3A Gerben. I apologize for not testing an answer before I post it.
Given the information only in this question Gerben's answer is complete, but since your other question implies that you cannot use OCR3A due to the Servo library I'll add a bit. (I've also edited that answer)
you can emulate the behavior of CTC mode by setting TCNT3 to 0 in your interrupt routine. Remember to remove the line that turns on CTC mode in your code.
I've tested your code with this ISR:
ISR(TIMER3_COMPB_vect)
{
  TCNT3 = 0;
  cont++;
}

and this configuration of the timer registers
OCR3B = 5208; // 800Hz 5; // 3 Hz
// Set CS10 and CS12 bits for 1024 prescaler:
TCCR3B |= (1 << CS30) | (1 << CS32);
// enable timer compare interrupt:
TIMSK3 |= (1 << OCIE3B);

This might be a bit less accurate at high frequencies than CTC, I'm not sure, but at 3Hz it worked perfectly. Notice that 5208 was the correct OCR value, not 20 (again thanks to Gerben).

I've tried your code but the counter isn't incremented. I've added the TCNT3=0; in the ISR() and removed
//TCCR3B |= (1 << WGM32); in the setup() as you said. I've also tried commenting out the cont=0; line but nothing changed

Make sure the code matches what is posted in the question in every other way. Try changing your loop to just println(cont); delay(1000);. Also you are still including the bits with cli() and TCCR3A etc correct?

Ok thanks. At 800 Hz is still accurate!


text:
Why can this color sensor not recognize green?
I got this color sensor last week, I've been able to get the sensor to recognize blue and red, but not green. still working on this.
I use the code in the product page.
so anybody have any idea about this issue? Pretty thanks.

Check that you've connected all the Arduino pins correctly to the sensor. In particular, make sure pin 4 on the Arduino is connected to S2 on the sensor.
It's the combination of signals on S2 and S3 which determines which colour is being detected:
S2    S3    Colour
----  ----  ------
Low   Low   Red
Low   High  Blue
High  Low   Clear
High  High  Green

If S2 is always low then you can only detect red and blue.
If the connections are definitely correct, then ensure you haven't made any code modifications which could interfere with it. You may also want to test pin 4 on your Arduino (e.g. using a multimeter) to make sure it's working properly. If necessary, you could use a different pin instead. However, you'll need to modify the #define S2 line in the code to match.

Wouldn't clear just be the color on the other side of the object? Or do you mean when it is out of range?

@AnnonomusPenguin That's the wording used in the datasheet. The device consists of a basic light sensor with a selectable colour filter. Clear means there's no filter, so it will simply detect the brightness of all visible light falling on it. If you apply the red filter, it mainly detects the brightness of red light, and so on. To detect the actual colour of something, you have to take three readings to get the RGB components; i.e. one with each filter applied.


text:
How to detect high/low signal from a DC servo motor using arduino?
I am a newbie to Arduino.
What I am going to do is to change my roll to roll printer to flatbed printer.
Rather using print roller, I decided to move the bed from a stepper motor.I know how to run the stepper motor for specific distance using arduino.
So I need to cheat printer to think that its roller is working and media is going through it.But actually what I am going to do is to monitor the printer motor running or not from arduino input and if the printer motor is running stepper motor will turn or if motor stops stepper motor must stop.
What my problem is how can I read that the dc servo motor status? How would I need to wire arduino input to servo motor to get the status.
Please show me some light on this.Sorry if this is a newbie question.
Thank you.

Any particular servo?

@IgnacioVazquez-Abrams sorry for posting external link.servo motor like this http://www.aliexpress.com/item/Hot-leadshine-dc-servo-motor-100W-24V-5-9A-2500r-min/862541888.html

Do you have the datasheet for it?

No I haven't.Can't we just check whether power comes or not?

How you will run the servo? With arduino? if so you can do software check

Is it a servo or a regular dc-motor? Does it have 2 wires, or 3?

@Martynas No it is run by my printer driver.when the printer is working I just need to hack the motor line get whether the motor is running or not.If motor runs I need to run stepper motor from arduino

This may not work very well. If it is an actual servo motor, it will run to close the error and achieve position, while your stepper just gets a "step".   You might be able to detect each "pulse" of movement and advance a line, but the simplest solution would be to use that motor for your flatbed mechanism.  If you can't do that, you could consider putting an encoder wheel on the motor and driving your stepper from those signals, either with some clever logic or a micro controller - effectively "electronic gearing"

Do you need to check if it is stalled? Or simply running?
Either way, you could check the voltage with an analogue input, compare against a threshold (empirically set) & use that. Take the voltage reading from the non-commoned side of the motor, after any driver circuit.
If you want stalled, a small resistance would help, if just running then you could get away with a digital input.
If the voltages aren't matched then a resistance divider chain would be necessary.

Thanks for the answer.No I just Need to check motor running or not.

I would definitely use an Opto-Isolator between the motor and the Arduino for these reasons.
You will have a problems with the grounds as the motor reverses.
The 24V supply.  If you get something slightly wrong then it will take out the Arduino and the PC connected to it.
The motor will generate large voltage spikes( circa 50..300Volts) under certain condions.  The Arduino and the PC connected to it will complain, but not for long!

Thanks alot for your answer.Since I am new to electronics I don't know how to connect those between arduino and motor.Can You explain it little bit deeper?

This would normally be handled with a series resistor and a diode clamp, potentially a bidirectional one.  That lets the Arduino sit at the ground potential of the motor driver and determine direction by watching the two sides of the motor.


text:
How to delay so that LED stays on a bit longer?
I have a circuit with a shift register which controls 8 LEDs: http://node-ardx.org/exercises/5. In code, I created a function cycle() cycle through each LED one at a time, but this occurs too quickly on the board. How can I add a delay inside the loop so that each LED stays on for 500ms?
Here's my code:
var five = require("johnny-five"), board, shiftRegister;

board = new five.Board();

board.on("ready", function() {
  shiftRegister = new five.ShiftRegister({
    pins: {
      data: 2,
      clock: 3,
      latch: 4
    }
  });

  var bytes = [
    00000001,
    00000010,
    00000100,
    00001000,
    00010000,
    00100000,
    01000000,
    10000000,
    00000000
  ];

  function cycle() {
      for ( var i = 0; i < bytes.length; i++ ) {
          console.log(bytes[i]);
          shiftRegister.send(bytes[i]);
      }
    }

  this.repl.inject({
    sr: shiftRegister
  });

  cycle();

});

The answer is already provided in the article.
  var i = 0;
  function cycle() {
    console.log(bytes[i]);
    sr.send(bits[i]);
    i++;
    if( i<bytes.length )
      setTimeout(cycle, 300);
  }

I don't want the cycle function to repeat. I do want to delay just after sending the new byte to the register just after changing the LEDs.

See edit above. It now only does one cycle.

Insert a delay of 500ms?
function cycle() {
    for ( var i = 0; i < bytes.length; i++ ) {
        console.log(bytes[i]);
        sr.send(bits[i]);
        delay(500);
    }
  }

JavaScript doesn't have a function called "delay".

Good job that's not the language we're discussing then!

Which variant of C or C++ is the "var" keyword supported in?

In that case you'll want this I imagine.

This isn't working for me. When I run the changes above, the REPL reports delay is not defined. I'm running Johnny Five v0.8.32. Where is delay defined by Johnny Five?


text:
Source Code for strcpy and strcat
Does anyone know the location of the assembler file for strcpy and strcat for the Arduino?  I wish to modify it.

I don't think these functions are written in assembler, but just in pure C. I am not sure it would be agood idea to modify them (but you could copy them into new functions and adapt the way you want it). Honestly, these functions are quite easy to write with just 1 or 2 lines of code. What are you trying to achieve?

The Arduino IDE doesn't ship with the source/assembly for a lot of the core functionality. It comes pre-compiled in object/library files.
However, you could download the source code for AVR Libc from this site:

http://www.nongnu.org/avr-libc

Obviously there's no guarantee that the files you download will exactly match what comes with the Arduino IDE, but it's useful if you're interested in how they're implemented.
When you've downloaded and extracted the source code, look in the libc/string folder. you should find assembly files called strcat.S and strcpy.S.
As jfpoilpret says in the comments, attempting to modify core library functions is generally not a good idea. They may be getting called by other parts of the core, so any changes you make could break something else.


text:
Are my arrays stored in sram or in Flash?
I have the following memory allocation:
unsigned char g1[]={
  0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ....0x00 ,0x00 ,0x00 ,0x00 ,0x00 };
g2[]={
  0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ....0x00 ,0x00 ,0x00 ,0x00 ,0x00 };
...

 unsigned char* index[10] = {g1,g2,g3,g4,g5,g6,g7,g8,g9,g0};

This is accessed in the following way:
unsigned char* getMatch(int input){
  return index[input];
}

This is then futher acces using the method of
unsigned char store[1024]
unsigned char* temp = getMatch(n);
for(int i=0;i <50;i++){
 store[i]=temp[i];
}

and store is then modified and send to an external device.
As my program is randomly failing I think it might be running low on SRAM and was wondering if there is any way to force this memory to be placed in flash. Anybody got an idea?

It's stored in both the FLASH and SRAM because it's initialized array. To store in FLASH only you need use PROGMEM attribute.
const unsigned PROGMEM char g1[]= ...

You cannot access directly but using memcpy_P() function.

How would I put this in the 2nd array after this? I get a lot of error: invalid conversion from ‘const unsigned char*’ to ‘unsigned char* errors.

Never mind got it.


text:
Arduino - Progamming issue
my first post here.
Anyway I'm working on a Simon Says game.
I have a weird bug with the function that reads button input.
This is the code:
int deBounce(int count){
  int pressed=-1;
  int laastButtons[3]; // save the previous deBounce read.
  for(int x; x<4; x++)
  {
    laastButtons[x] = lastButtons[x];
    lastButtons[x] = !digitalRead(button[x]);
    if(lastButtons[x] == true)
    {
      delay(50);
      lastButtons[x] = !digitalRead(button[x]);
      if(lastButtons[x] == 1){ pressed = x;}
      nt("Pressed!, Button ID: ");nt(x); nt(" pressed:  ");nt(pressed); nt(" state "); ntln(lastButtons[x]);
    }
  }
  if((lastButtons[0] + lastButtons[1] + lastButtons[2] + lastButtons[3]) > 1)
  {
    ntln("ERROR: dont press more than one button at a time. ");
  }
  if( ((lastButtons[0] + lastButtons[1] + lastButtons[2] + lastButtons[3]) == 1 ) && !laastButtons[pressed] && (pressed != -1) ) {
    pressButtons[count] = pressed;
    nt("Pressed!, ID: ");nt(count); nt(" Button ID ");ntln(pressed);
    return count++;
  }else return count;
}

This is what I recieve in the Serial Monitor if I press one of the buttons.

Pressed!, Button ID: 3 pressed: -1 state 1

How is that possible? Note the lines where that line is printed and the line above it.
Seems like that if should run, but the line pressed = x; doesn't function.
Note that, nt and ntln are just a short for Serial.print.
I have this weird bug and sometimes it seems like the chip is glitching!
Another question is- I tried attaching interrupt and it didn't worked,
Is it possible that my board is not compatiable with them? (It's not original).
Thanks.
EDIT:
After Majenko helped me figure it out,
The thing that created the bug was that I expected a x==0, but I didn't define it in the for loop.
Before:
for(int x; x<4; x++)

After:
for(int x=0; x<4; x++)

Thanks again Majenko!

int laastButtons[3]; // save the previous deBounce read.
for(int x; x<4; x++)
{
   laastButtons[x] = lastButtons[x];

Well, there's a common bug right away.  An array with three slices, numbered 0, 1 and 2, and you're accessing them with a loop that counts from 0 to 3.
Spot the error.
Also, in the for loop, what number does it start counting from?
And now for your "bug".  This block of code:
if(lastButtons[x] == true)
{
  delay(50);
  lastButtons[x] = !digitalRead(button[x]);
  if(lastButtons[x] == 1){ pressed = x;}
  nt("Pressed!, Button ID: ");nt(x); nt(" pressed:  ");nt(pressed); nt(" state "); ntln(lastButtons[x]);
}

I think you have it slightly wrong.  Let's convert it into plain english:

If button is pressed:

Delay 50 ms
Read button again
If button is pressed:

Set pressed to the button number

Print the button message

Note the indenting, which highlights what gets executed for what IF statement.  The print is going to happen regardless of the setting of the pressed variable.
I think the structure you wanted is:

If button is pressed:

Delay 50 ms
Read button again
If button is pressed:

Set pressed to the button number
Print the button message

In that layout the second If is controlling both the setting of the pressed variable as well as whether or not to print the Pressed! message.
if(lastButtons[x] == 1){ pressed = x;}

That line is saying "If last buttons X is 1, then set pressed to X. That is all it is doing. Nothing more, nothing less.


text:
Wireless serial communication. Sending 4 different continuous values
I am trying to control 4 motors using 2 joysticks.
I want to send continuous analog values of 2 joysticks (x & y both).
I am using bluetooth HC-05. I am using the basic logic that is sending a character before each analog value and thus sending all 4 values.
My problem here is at the reception end, data is not received correctly. Error rate is very high.
Is their any other way or improved program to do that?
//this is my part of the code at the transmitter side

#include <SoftwareSerial.h>
int a,b,c,d;
int ry = A0; // forward backward
int rx = A1;//rotate
int lx = A3; //right left
int ly = A4;
SoftwareSerial blu(10, 11); // TX,RX

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

void loop()
{

   a = analogRead(ry)/4;
   d = analogRead(rx)/4;
   c= analogRead(ly)/4
   b = analogRead(lx)/4;

   blu.write("w");
   blu.write(a);
   blu.write("x");
   blu.write(b);
   blu.write("y");
   blu.write(c);
   blu.write("z");
   blu.write(d);
      }

}

// Code at the reciever side

#include <SoftwareSerial.h>

SoftwareSerial mySerial(12,13); // tx,rx

void setup()
{
  Serial.begin(9600);
  mySerial.begin(9600);
  digitalWrite(gnd1 , LOW);
  digitalWrite(gnd2 , LOW);

  pinMode(motor1, OUTPUT);
  pinMode(motor2, OUTPUT);

  pinMode(dir1, OUTPUT);
  pinMode(dir2, OUTPUT);
  pinMode(dir_1, OUTPUT);
  pinMode(dir_2, OUTPUT);

}

void loop()
{
    if (mySerial.available())
  {
    a=mySerial.read();
        if(a=='w' || z=='x' || a=='y' || a=='z')
        {
          if(a=='w')
        c_b=mySerial.read();
        b=map(c_b,0,255,-255,255);
        motorspeed1(b);
      }
   if(a=='x'){

            int c_c=mySerial.read();
            b=map(c_c,0,255,-255,255);
            motorspeed2(c);

          }
if(a=='y'){
 int c_d=mySerial.read();
            d=map(c_d,0,255,-255,255);
            motorspeed3(d);
  }
if(a=='z'){
 int c_e=mySerial.read();
            e=map(c_e,0,255,-255,255);
            motorspeed3(e);

}
}

//motor speed function takes care of the direction and the pwm. my problem is at the receiving end the values are not proper . error is very high mySerial.read() gives false values

Can you post the parts of the code that send and parse the messages? how about examples of what is being received? Can you tell if the error rate is due to the protocol or interference?

The problem could be baud rate, not correctly taking data or anything. As @BrettM said, we need more information. Also you say 4 motors and 2 joysticks. Do you have X1&Y1 and X2&Y2? You could send 6 bytes: Start byte,4 data bytes(0..255) and stop byte

guys i have included the code. thanks for the reply


text:
Delay on multiple NRF24L01+ (RF24.h) and Arduino nodes
I have set up a system using 4 arduino clones, each wired to an NRF24L01+ radio. I am using the RF24 library by maniacbug (https://github.com/maniacbug/RF24) and have set-up the nodes with 1 base node as a receiver and 3 child nodes that transmits continuously to the receiver.
What I want to do is to send the read and analog value wirelessly from the child nodes to the base node as fast as possible. I used the starping example as a guide and it looks almost realtime when only 1 child node is active. When I turn on another child node, most of the time the update stops for a while then continue on, with randomly updating either child 1 or child 2.
I'm guessing there's a collision that's causing the delays. How do I lessen these delays? I'm thinking of having some sort of scheduling system for the children to send their messages (like, child2 will send only after child1, etc.) I also tried radio.setAutoAck(false) in an attempt to lessen the delays but that made all my readings stop altogether.
base node:
    #include "Timer.h"
    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    #include "printf.h"

    RF24 radio(9,10);
    Timer t;

    const uint64_t pipes[5] = { 0xF0F0F0F0D2LL, 0xF0F0F0F0C3LL, 0xF0F0F0F0B4LL, 0xF0F0F0F0A5LL, 0xF0F0F0F096LL };
    unsigned int values[3] = {0,0,0};
    void setup(void)
    {

      Serial.begin(115200);
      printf_begin();
      //printf("Receiver Node Active\n\r");

      radio.begin();

        radio.openReadingPipe(1,pipes[0]);
        radio.openReadingPipe(2,pipes[1]);
        radio.openReadingPipe(3,pipes[2]);
        radio.openReadingPipe(4,pipes[3]);
        radio.openReadingPipe(5,pipes[4]);

      radio.startListening();
      radio.printDetails();
      t.every(1, print_values); //call print_values() every 1ms

    }

    void loop(void)
    {
        int sender_id;
        uint8_t pipe_num;
        if ( radio.available(&pipe_num) )
        {
          unsigned int message;
          bool done = false;
            while (!done)
            {
                done = radio.read( &message, sizeof(message) );
            }
          sender_id = pipe_num - 1;
          values[sender_id-1] = message;
        }
        delay(1);
        t.update();

     }

     void print_values(){
       //formatted for arduinoscope
       printf("%d %d %d 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n", values[0], values[1], values[2]);
     }
    // vim:ai:ci sts=2 sw=2 ft=cpp

child node:
    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"

    RF24 radio(0,1);

    const int SW01 = 18;
    const int SW02 = 19;

    const uint64_t pipes[5] = { 0xF0F0F0F0D2LL, 0xF0F0F0F0C3LL, 0xF0F0F0F0B4LL, 0xF0F0F0F0A5LL, 0xF0F0F0F096LL };
    int node_id;

    void setup(void)
    {
      node_id=3; //hard coded id
      radio.begin();
      radio.openWritingPipe(pipes[node_id]);
    }

    void loop(void)
    {
        unsigned int val = analogRead(A0);
        radio.write( &val, sizeof(val) );
        //delay(1);
    }

You could have the receiver poll the transmitters instead. Maybe using writeAckPayload.

I'd suggest you'd update your library to this.

I am too building a RF24 based network there were two issues I encountered:
1) Update your libraries, use TMRh20 fork of RF24 (to make your life easier, use RF24Mesh too)
2) Add a decoupling cap to the NRF24L01+ power pins.

I can think of 3 ways:

You could have the Base polling for updates to each node
sequentially, or
If all child nodes see each other, node2 can hear when node1
finished transmitting so it can transmit and so on. Or
You can punch through collisions setting random delays between each
retry

1) Since these are all one-way communication, disable AutoAck on all NRFs (setAutoAck(false)). You're not doing Ack anyway which will cause retransmission when not acknowledged.
2) Change the address to something better.
Addresses where the level shifts only one time (that is, 000FFFFFFF) can often be detected in noise and can give a false detection, which may give a raised Packet Error Rate. Addresses as a continuation of the preamble (hi-low toggling) also raises the Packet Error Rate
3) Put a capacitor between ground and Vcc on all NRFs.


text:
How to prevent Arduino compiler from merging changing of port pin outputs into a single operation
I want to set one pin's output value, and then set a different pin's output value so that the two pins change value one after the other.
However, the compiler optimises the two calls to change both pins in one go.

PORTD |= _BV(0);    //set pd0 to high
PORTD |= _BV(1);    //set pd1 to high
PORTD &= ~(_BV(1)); //set pd1 to low

The two pins go high simultaneously. I tried inserting a NOP between these but it doesn't change behaviour.
(I originally intended to include an oscilloscope screengrab to show what was happening - that's how I knew (or got the wrong impression) that the two pins were changing at the same time. But the photo wasn't shifting from my Nexus 7 for me to access it from my laptop.)

I can't duplicate this behavior. Which version of GCC is in use?

What application requires those pins to be turned on one after the other, but so quickly that you don't need any code to cause a delay between the two?

Cool - there's an Arduino stackexchange! Thanks to the mods for migrating the question.

It sounds like I've just got myself confused here, since the behaviour I've seen isnt repro-able.

(by others, that is).

Granted I'm no expert on O-scopes, but given that the pin changes with separate calls will still happen in tens of nanoseconds, could a scope accurately detect the difference?

Well, when testing this as its own sketch I can see everything working properly - the delays between signal changes are quite evident.

I certainly can't duplicate what you are saying.  The small code snippet:
void setup() {
    PORTD |= _BV(0);
    PORTD |= _BV(1);
    PORTD &= ~(_BV(1));
}

void loop() {
}

compiles into:
000000a6 <setup>:
  a6:   58 9a           sbi 0x0b, 0 ; 11
  a8:   59 9a           sbi 0x0b, 1 ; 11
  aa:   59 98           cbi 0x0b, 1 ; 11
  ac:   08 95           ret

000000ae <loop>:
  ae:   08 95           ret

That is clearly two separate bit sets followed by a bit clear.
I am using UECIDE that is set to use GCC 4.3.2
If I switch to GCC 4.8.1 instead, the code generated is identical.
Even turning on full -O3 optimization I still get the same results.
So how are you determining that it's happening at the same time?

Which makes sense since the memory location has been declared as volatile.

I think I'm using Arduino IDE 1.06 but I will need to check when I get home.

I observed the two pins changing on an oscilloscope, but I will have to take a step back and do a test with the Arduino Micro removed from the project I'm working on. Sounds like I'm just mistaken.

Same code generated here with avr-gcc 5.4.0.