Connect the Sparkfun CAN bus shield with an RFduino I have a problem which I am working on for some days now. I do have knowledge in electronics, but not extensively. I also posted this question in the RFduino Forum but couldn't get any good answers.

What I am trying to do: I want to connect the Sparkfun CAN bus shield to the RFduino. I am using the code further below. It compiles without problem and does work with my Arduino Leonardo!

I used a logic analyser (ignore the filled shapes, some display error) to further narrow down the problem and found the following on the RFduino:

On the Leonardo, it looks different:

It seems like I don't get a response on the MISO line! I played around with different speeds, but nothing seemed to work.

I do have a suspicion however: The RFduino works with 3.3V, while the Leonardo works with 5V. So the logic signals on the RFduino can only achieve 3.3V P-P. I confirmed this with my old CRO, LOW is at GND and HIGH at 3.3V. The Leonardo has 5V P-P.
On page 70 of the datasheet for the MCP2515 (the chip used on the shield), it says that the supply voltage VDD ranges from 2.7V to 5.5V. So supply voltage should be ok. V_INPUT_HIGH ranges from 2.31 to 4.3V. V_INPUT_LOW ranges from -0.3V to 0.495V. I am in this range! Similarly so for the V_OUTPUT_LOW (up to 0.6V) and V_OUTPUT_HIGH (at least 2.8V). Could this nevertheless be a problem?

What would you try or change?

MCP2515 Datasheet

#include <SPI.h>

// demo: CAN-BUS Shield, send data
#include <mcp_can.h>

MCP_CAN CAN0(SS);                                      // Set CS to pin 10

unsigned char stmp[8] = {0, 1, 0, 3, 0, 5, 0, 7};

void setup()
{
  Serial.begin(115200);
  while (!Serial) {
    ;                  // wait for serial port to connect. Needed for Leonardo only
  }
  // init can bus, baudrate: 500k
  if(CAN0.begin(CAN_500KBPS) == CAN_OK) Serial.print("can init ok!!\r\n");
  else Serial.print("Can init fail!!\r\n");
               // send data per 100ms
}

void loop()
{
//    // send data:  id = 0x00, standrad flame, data len = 8, stmp: data buf
//  CAN0.sendMsgBuf(0x00, 0, 8, stmp);
}

Ok, I found the solution. The fix first: I had to physically connect the reset line from the RFduino to the MCP2515 reset pin.
On page 55 in the datasheet of the MCP2515 it says that you can either reset it by pulling the reset line low or by sending a command over the SPI. The library I used is sending this reset command, but it isn't working for some reason. The logic analyser shows me this signal, it is the first recorded. Maybe it is a timing issue, that the reset has to be sent at the same time as the RFduino resets. Connecting the reset pin solves this issue, because then the RFduino and the MCP2515 are being reset at the same time.
If anybody knows more about this, feel free to tell me!


defining a macro with variables I am working on Marlin 3D program. I made some changes for xyz prop and I do not make a definition as #define PRB_GCODE_END "G92 X-" XOFF "Y" XOFF "Z" ZOFF "\ n" to send the final xyz coordinates as gcode at the end of the promulgation procedure. It is required. If anyone has any idea how to use float type variables during macro definition please help.
void _user_gcode_exe(const char * const cmd) {
  lcd_return_to_status();
  enqueue_and_echo_commands_P(cmd);
}

void user_gcode_exe_1() {
  float XOFF = (25.00 + PRB_XOFFSET + (TOOL_DIA / 2.00));
  float YOFF = (25.00 - (PRB_YOFFSET + (TOOL_DIA / 2.00)));
  float ZOFF = (10.00 + PRB_ZOFFSET);

#define PRB_GCODE_END "G92 X-" XOFF " Y" XOFF " Z" ZOFF "\n"

#define PRB_GCODE "M117 Z-XY Probing now..\nG38.2 F120 Z-20.00\nG92 X0.00 Y.00 Z0.00\nG0 Z5.00 F1200\nG0 X-20.00 F1200\nG0 Z-5.00 F1200\nG38.2 F120 X25.00\nG92 X0.00\nG0 X-5.00 Y-25.00 F1200\nG0 X15.00 F1200\nG38.2 F120 Y25.00\nG92 Y0.00\nG0 Y-5.00 F1200\nG0 Z10.00 F1200\nG0 X-25.00 Y25.00 F1200\n"

#define MSG__OK "M117 Z-XY Probing done..\n"
  _user_gcode_exe(PSTR(PRB_GCODE PRB_GCODE_END MSG__OK));
}

While defining PRB_GCODE_END, ensuring that float type variables are included in this definition. For example: Considering that the variables XOFF, YOFF and ZOFF are calculated as 12.85, 11.25 and 10.50 respectively. PRB_GCODE_END should occur as follows:
G92 X-12.85 Y 11.25 Z10.50 \n

You can't. Variables and macros are completely different concepts and handled by completely different parts of the compiler toolchain.
Instead you will need to build your string up into a char array (or whatever format the _user_gcode_exec() function accepts) with the likes of sprintf.


sending 16 bit command via SPI to a NCV7719 (half bridge) I am trying to send a 16 bit command to a Half bridge (data sheet here http://www.onsemi.com/pub/Collateral/NCV7719-D.PDF) to open one of the transistors to turn on an LED. at the bottom of the data sheet (page 13) it says which bit needs to be a 1 or a 0 in order to activate the half bridge. This is the code I wrote but it isn't work (I'm assuming I'm not sending the 16 bits properly). Can someone figure out why this isn't working?

#include <SPI.h>

void setup() {
  // put your setup code here, to run once:
  pinMode(10,OUTPUT);
  pinMode(8,OUTPUT);
  digitalWrite(8,HIGH);
  SPI.begin();

}

void loop() {
  // put your main code here, to run repeatedly:

  //pulling pin low to decide to write to device
  digitalWrite(10,LOW);

  //function to send information
  //truning on half bridge 4
  SPI.transfer(0000010000000000);
delay(500);
  //finish transfering data
  digitalWrite(10,HIGH);

}

SPI writes in 8-bit bytes. So the writes need to look like this:

  SPI.transfer(0b00000100);  // first byte
  SPI.transfer(0b00000000);  // second byte

Possibly in the other order depending on which byte the device expects first.


Are there any Analog pins on the mega that can not be used as Digital? I am using both Arduino nano and Arduino mega boards in my projects.  I got a nasty surprise the other day when I learned that, on the nano, Analog pins 6 and 7 can not be used as digital pins.

Are there any Analog pins on the mega that can not be used as Digital?

No, the ATmegaXXX0 has no analog pins without GPIO capability.

Additionally, the ATmegaXX8PB adds GPIO capability to the other analog pins plus a couple of the supply pins, so if you can convince someone to slip one of those on instead then you will gain two GPIOs (a respin will be required to access the ones on supply pins). Note that the core will also need to be modified, but it's only a couple of quick changes.


Powering Multiple Servos From One Battery- What is my circuit missing? I'm working on a robotics project right now and my limited DIYer knowledge of electrical circuits is failing me. I need to power 7 Rage Standard Metal Gear Servos (RGRS104-16-6vm) and 4 RadioShack Micro Servos using a Tenergy 6V 3300mAh NiMH Battery Pack. I've made a diagram of the circuit I'd like to make, but I feel like there's more to this type of circuit than I've planned for. There are only 9 servo connections because two pairs of Rage Servos will be wired together to share the same battery and signal connection. I'm also open to using a different battery if that's what it takes to make the robot run smoothly (It has to use a rechargeable battery though; It's meant to be portable.) Also, the Arduino has it's own battery, so no worries there.

Would you please point out what I need to add to my circuit to make sure it works properly?

Thanks in advance!

More Info:

Rage Standard Metal Gear Servo RGRS104-16-6vm
Dimensions: 40.8 × 20.1 × 38 mm
Weight: 56 g
Operating Speed: 0.18sec/60degree (4.8V), 0.16sec/60degree (6V)
Stall Torque: 9kg.cm/125.2oz.in(4.8V), 10.2kg.cm/141.9oz.in(6V)
Operating Voltage: 4.8V~6V
Control System: Analog
Direction: CCW
Operating Angle: 180degree
Required Pulse: 500us-2500us
Bearing Type: 2BB
Gear Type: Metal
Motor Type: Carbon
Connector Wire Length: 30 cm.

RadioShack Micro Servo
Voltage: 4.8~6.0V
Torque: 1.5kg/cm at 4.8V; 1.8kg/cm at 6.0V
Speed: 0.12/60ТА at 4.8V; 0.10/60ТА at 6.0V
Size: 23x11.5x24mm
Weight: 8.6 g
Use Angle: <=160ТА

Tenergy 6V 3300mAh NiMH Battery Pack
Chemistry: Ni-MH
Cell Size: Sub-C
Nominal Voltage (V): 6
Capacity (mAh): 3300
Max Continuous Discharge Current: 6A
Battery Charging Current:
Standard: 1A
Weight: 10oz.
Dimensions: 112 x 46 x 23mm (LxWxT)
Connector: Hitech

Link to Diagram: http://imgur.com/BRrWijV

One thing to ask, it is not clear if you are going to run the Arduino Uno off the same battery, or off a different battery?

If the same battery, then you are likely going to need to create an V+ output for the Uno, but will need to ensure that any drain from multiple servo's running are not going to impact on the voltage supplied to the arduino, and also that the voltage supplied is compatiable with the Uno (e.g. don't run 6V+ into the 3V outlet)

Just to note as well, the Arduino Uno has (to my knowledge) only has about 6 PWM pins which is what you will need to drive the servo's through the signal pin. You can add I2C PWM expanders which give you more pins (e.g. https://www.adafruit.com/product/815) but YMMV


Power Supply for 30 Servos I am now constructing something with 30 servos (each one will control an individual joint separately, so I guess I can't get away from this), how can I determine how much current do I need, I have a 5V 6A power supply, will that be working just fine? Many thanks in advance!

Get one of the servo's working at full load & measure the current flowing through it, multiply that by 30.

That's a lot of servos :D


Where are the implementations of the SdFat BlockDriver methods? This is most probably more of a C++ question than an Arduino question; but since this is an Arduino library, I am asking here.

I am using the SdFat library for my project. The library defines a BlockDriver object in one of its header file which only declares the typedef of BaseDriver to some other classes.

#if ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
typedef BaseBlockDriver BlockDriver;
#else  // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
typedef SdSpiCard BlockDriver;
#endif  // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
#endif // BlockDriver_h

typedef SdSpiCard BlockDriver; makes sense to me. But if ENABLE_EXTENDED_TRANSFER_CLASS or ENABLE_SDIO_CLASS are defined, BlockDriver is typedeffed into BaseBlockDriver. BaseBlockDriver is an abstract base class (as defined here). An instance of the BlockDriver object is later used directly in the FatVolume class here.

My question is, how does BlockDriver's method get defined when it abstract base class BaseBlockDriver is typedeffed to BlockDriver?

The typedef in BlockDriver.h is only for pointer type, not for instance of the object. The object is always of type SdSpiCard, but in one case it is not an implementation of BlockDriverBase, so the function parameters can't refer it by base type.

#if ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
class SdSpiCard : public BaseBlockDriver {
#else  // ENABLE_EXTENDED_TRANSFER_CLASS || ENABLE_SDIO_CLASS
class SdSpiCard {

use of BlockDriver typedef

class FatFileSystem : public  FatVolume {
 public:
  bool begin(BlockDriver* blockDev, uint8_t part = 0) {

I was curious why the version without BaseBlockDriver. I asked the author Bill Greiman and he answered:

  This is due to history. Long ago using a virtual base class cost lots
  of RAM and flash so I did this mainly for 328 boards


Multiway Relay Dimmer I am looking for something like a multiway "relay dimmer".
Which lets me dim a light using an Arduino and a manual dimmer.

(The manual dimmer should work without any computer!)

You could use a rotary encoder for that purpose!

Basically the rotary encoder is a knob that, for every "tick" you give it, it returns a different value to your Arduino. With a bit of programming you can sense the direction of the turn, if it is positive then you lighten up the LED, and vice versa.

I used that to control a RGB led, it works very well! here some more information on the rotary encoder and the code needed to use it.


Parsing Int over Serial Slow I am trying to communicate between my PC and Arduino Mega 2560 using this serial library. It works reliably, however I am having trouble passing messages at a high rate over serial. I set the baud to 460800 bps on both systems, and am using a serial handshake. The Arduino reads the values by parsing a string, however during my testing I cannot parse more than ~240 messages per second. Each message into the Arduino is either of the form "r/n" to reset some variables or "0,0,0\n" where in this case the zeroes are the ints I want to parse, these can change. My Arduino code in the loop is as follows:

if(Serial.available() > 0){
  resultString = Serial.readStringUntil('\n');
  if(resultString.equals("r")){
    countEnc0 = 0;
    countEnc1 = 0;
    countEnc2 = 0;
  }else{
    int counter = 0;
    int lastIndex = 0;
    for (int i = 0; i < resultString.length(); i++) {
      // Loop through each character and check if it's a comma
      if (resultString.substring(i, i+1) == ",") {
        // Grab the piece from the last index up to the current position and store it
        write[counter] = resultString.substring(lastIndex, i).toInt();
        // Update the last position and add 1, so it starts from the next character
        lastIndex = i + 1;
        // Increase the position in the array that we store into
        counter++;
      }
      // If we're at the end of the string (no more commas to stop us)
      if (i == resultString.length() - 1) {
        // Grab the last part of the string from the lastIndex to the end
        write[counter] = resultString.substring(lastIndex, i+1).toInt();
      }
    }
    analogWrite(8, write[0]);
    analogWrite(9, write[1]);
    analogWrite(10, write[2]);
  }
  Serial.println(String(countEnc0) + "," + String(countEnc1) + "," + String(countEnc2));
}

I know there are more efficient ways to parse this, however my attempts to use them yield similar results (Using parseInt(), char*, etc). Additionally, I am using 3 interrupts to read sensor values and store them in variables here, and writing the values I acquire to the PWM. As long as I can read and send up to 1000 messages per second that's all I need for now. Many thanks...been banging my head against the wall on this one.

First off, I would recommend  strtok or even getline to parse comma delimited strings.

Secondly, I'm pretty sure no PWM is responsive enough for 1000 updates per second. But for other purposes this data rate might be needed.

To do this, build a custom cache that does the following:

Reads 1000 characters per go, if available, or less.
Parses on the go. From this set up callbacks to you PWM class, so that you can set PWM values while parsing.

Why this? I am not convinced that the sluggishness is due to the for parsing data. More likely, it's because you are processing every instruction as you get it.

1000 serial reads with 6 length for loops over strings (your case) will be significantly slower than 1 serial read and a 6k length for loop.


Client or WiFiClient wrapper for adafruit CC3000 wifi I have a CC3000 wifi module from adafruit that is working OK. Now, I am trying to use it together with an external service, which code requires me to pass a Client (from Arduino SDK) reference, but the Adafruit_CC3000_Client does not inherit from Client nor WifiClient.

I am looking for an appropiate wrapper, but unable to find one. Does anyone know about such wrapper?

As I didn't get any answer, and further search for an existing solution failed, I decided to roll my own. The class header is very straightforward, I decided to go for single inheritance and composition of Adafruit_CC3000_Client:

class CC3000Client: public WiFiClient {
public:
    CC3000Client(Adafruit_CC3000& cc, Stream& stream=Serial);
    virtual ~CC3000Client();

    virtual int connect(IPAddress ip, uint16_t port);
    virtual int connect(const char *host, uint16_t port);
    virtual uint8_t connected();
    virtual int available();
    virtual void stop();
    virtual void flush();
    virtual int peek();
    virtual int read();
    virtual size_t write(uint8_t v);
    virtual size_t write(const uint8_t *buf, size_t size);
    virtual int read(uint8_t *buf, size_t size);
    virtual operator bool();

private:
    Adafruit_CC3000& cc3000;
    Adafruit_CC3000_Client client;
    bool peeked;
    int peeked_byte;
    Stream& stream;
};

The implementation is a bit tricky (or I didn't manage to find a better way), as the Adafruit client does not have peek() functionality, so this wrapper class have to implement it.

CC3000Client::CC3000Client(Adafruit_CC3000& cc, Stream& stre) :
        cc3000(cc), peeked(false), stream(stre), peeked_byte(0) {
}
CC3000Client::~CC3000Client() {
}

int CC3000Client::connect(IPAddress ip, uint16_t port) {
    client = cc3000.connectTCP((uint32_t) ip, port);
    peeked = false;
    if (client.connected())
        return 1;
    return 0;
}
int CC3000Client::connect(const char *host, uint16_t port) {
    uint32_t ip = 0;
    if (!cc3000.getHostByName((char*) host, &ip)) {
        stream.println(F("Couldn't resolve!"));
        return 0;
    }
    client = cc3000.connectTCP(ip, port);
    peeked = false;
    if (client.connected()) {
        return 1;
    }
    return 0;
}
uint8_t CC3000Client::connected() {
    return (uint8_t) client.connected();
}
int CC3000Client::available() {
    if(peeked)
        return 1;
    return (int) client.available();
}
void CC3000Client::stop() {
    peeked = false;
    flush();
    while (client.connected()){
        client.close();
        delay(10);
    }
}
void CC3000Client::flush() {
    peeked = false;
    while (connected() && available())
        read();
}
int CC3000Client::peek() {
    if (!peeked) {
        if (available()) {
            peeked_byte = read();
            peeked = true;
        } else
            return -1;
    }
    return peeked_byte;

}
int CC3000Client::read() {
    if (peeked) {
        peeked = false;
        return peeked_byte;
    }
    return (int) client.read();
}
size_t CC3000Client::write(uint8_t v) {
    return (size_t) client.write(v);
}
size_t CC3000Client::write(const uint8_t *buf, size_t size) {
    return client.write(buf, size);
}
int CC3000Client::read(uint8_t *buf, size_t size) {
    if(peeked){
        buf[0]=peeked_byte;
        peeked=false;
        return client.read(buf+1, size-1);
    }
    return client.read(buf, size);
}
CC3000Client::operator bool() {
    stream.println("Error, bool() not implemented");
    return true;
}

Both files are available here, if you are using biicode all you have to do in your code is to put an include like the following and run "bii find", that will also retrieve and install the cc3000 library:

#include "diego/ardunet/cc3000client.h"

I have used and tested it with a simple http_get call (also here) and with the temboo service, and it has worked OK for sending emails from a Gmail account from an Arduino Mega2560 connected to the CC3000. This temboo service uses via the SDK Client interface most methods of this wrapper, but the bool() operator and the CC3000Client::write(const uint8_t *buf, size_t size) method.


Why is no PWM signal generated using Timer 2? I managed to work with timer 0 and 1 but am unable to generate a PWM with timer 2 in my atmega328p.

This is the code:

#include <avr/io.h>

int main(void)
{
    /* PD6 output */
    DDRD |= (1 << DDD6);

    /* 50% duty cycle */
    OCR2A = 128;

    /* fast PWM  */
    TCCR2A |= (1 << WGM21) | (1 << WGM20);

    /* prescaler = 8 */
    TCCR2B |= (1 << CS21);

    while (1);

}

Could someone explain what the issue is and why I am not seeing a pwm signal on pin 6 of my arduino uno board?

Thanks

The output compare unit of timer 2 is connected to pins PB3 (OC2A) and PD3 (OC2B). So you have to configure those as outputs.
Keep in mind that you can't choose any pin when using hardware pwm, this hardware feature is linked to specific pins.

You also have to set COM2A1 in TCCR2A. Otherwise OC2A is disconnected from the output compare unit (ref: Table 17-3 in datasheet).
The effect of COM2A0/1 depends on the configuration in WGM20-WGM22.
The same applies to OC2B respectively.


Read RC receiver channels using Interrupt instead of PulseIn I am designing my own quadcopter control algorithm, whereby I currently read 4 RC receiver channels using PulseIn on each loop in the following manner:

ch1_raw = pulseIn(rcPin1, HIGH, 25000);

In other words, ch1_raw contains the length of a HIGH pulse in microseconds.

I now want to avoid PulseIn in the interest of speed and instead achieve the same using interrupt.

I have looked at http://playground.arduino.cc/Main/PinChangeIntExample and I am aware that other similar questions have been asked (e.g. How to read RC receiver channels without using pulsein() command with arduino and Is PulseIn fast enough for Quadcopter?), but I don't understand how to implement interrupt to give me the correct ch1_raw value on each loop.

Can somebody help me? (I'm new to Arduino, so go easy on me please!) Thanks!

Edit:
So far I have tried to implement the following:

#include <PinChangeInt.h>

unsigned long pulsestart, pulsewidth;

int rcPin1 = A0;

void setup(){

  pinMode(rcPin1, INPUT);

  Serial.begin(9600);

  PCintPort::attachInterrupt(rcPin1, counttime,RISING);
  PCintPort::attachInterrupt(rcPin1, subtracttime,FALLING);

}

void loop(){

  Serial.print("  pulsewidth: ");
  Serial.println(pulsewidth);

}

void counttime()
{
  pulsestart = micros();
}

void subtracttime()
{
  pulsewidth = micros()- pulsestart;
}

Edit 2:
(Somewhat) successful implementation so far, using EnableInterrupt.h instead. It seems that FALLING is being detected, but not RISING.

#include <EnableInterrupt.h>

#define rcPin1 10

volatile uint16_t pulsestart=0;
volatile uint16_t pulsewidth=0;
//volatile unsigned long pulsestart=0;
//volatile unsigned long pulsewidth=0;
volatile uint16_t risingcount=0;
volatile uint16_t fallingcount=0;

void counttime()
{
  pulsestart = micros();
  risingcount++;
}
void subtracttime()
{
  pulsewidth = micros()- pulsestart;
  fallingcount++;
}

void setup() {
  Serial.begin(9600);
  pinMode(rcPin1, INPUT_PULLUP);
  enableInterrupt(rcPin1, counttime, RISING);
  enableInterrupt(rcPin1, subtracttime, FALLING);
}

void loop() {
  //delay(1000);
  Serial.print("risingcount: ");
  Serial.print(risingcount);
  Serial.print(" fallingcount: ");
  Serial.println(fallingcount);
  //Serial.print("pulsewidth: ");
  //Serial.println(pulsewidth);
}

Regarding the question, “Does PinChangeInt only work on digital pins?”, note that PCI's work on all the digital pins of an ATmega328, and on the first six analog pins.  (32-pin '328s have eight analog pins, A0-A7; 28-pin '328s only six, A0-A5.)

Regarding the problem symptom that “pulsewidth just seems to increase continuously”, that could happen if for some reason rising edges aren't processed.  To debug, add a couple more volative byte variables, say nrises and nfalls; increment each of them in the appropriate interrupt handler; and report their values from time to time.

Regarding your #include <PinChangeInt.h> statement, note that PinChangeInt.h is deprecated (as of 3 April 2015).  Consider using EnableInterrupt.h instead.

It's possible you'll resolve your problem while changing libraries.  If so, fine.  If not, or if that library's performance isn't adequate, consider changing over to handling the  pin change interrupts more directly.  The ISR in the following sketch shown below runs several times faster than code that uses PinChangeInt or EnableInterrupt library calls.

[Edit: This edit encloses the ISR in a sketch that compiles.  The code previously shown was missing two array length specifications.  This code was tested with a rotary encoder attached to A2, A3, with A0 and A1 grounded; an output sample (using an Arduino Nano) follows the code.]

/*  rcTiming.ino -- JW, 30 November 2015 --
 * Uses pin-change interrupts on A0-A4 to time RC pulses
 *
 * Ref: http://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
 *
 */
#include <Streaming.h>
static   byte rcOld;        // Prev. states of inputs
volatile unsigned long rcRises[4]; // times of prev. rising edges
volatile unsigned long rcTimes[4]; // recent pulse lengths
volatile unsigned int  rcChange=0; // Change-counter

// Be sure to call setup_rcTiming() from setup()
void setup_rcTiming() {
  rcOld = 0;
  pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
  pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt
  pinMode(A2, INPUT);
  pinMode(A3, INPUT);
  PCMSK1 |= 0x0F;       // Four-bit mask for four channels
  PCIFR  |= 0x02;       // clear pin-change interrupts if any
  PCICR  |= 0x02;       // enable pin-change interrupts
}
// Define the service routine for PCI vector 1
ISR(PCINT1_vect) {
  byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
  byte changes = rcNew^rcOld;   // Notice changed bits
  byte channel = 0;
  unsigned long now = micros(); // micros() is ok in int routine
  while (changes) {
    if ((changes & 1)) {  // Did current channel change?
      if ((rcNew & (1<<channel))) { // Check rising edge
        rcRises[channel] = now;     // Is rising edge
      } else {              // Is falling edge
        rcTimes[channel] = now-rcRises[channel];
      }
    }
    changes >>= 1;      // shift out the done bit
    ++channel;
    ++rcChange;
  }
  rcOld = rcNew;        // Save new state
}

void setup() {
  Serial.begin(115200);
  Serial.println("Starting RC Timing Test");
  setup_rcTiming();
}

void loop() {
  unsigned long rcT[4]; // copy of recent pulse lengths
  unsigned int rcN;
  if (rcChange) {

    // Data is subject to races if interrupted, so off interrupts
    cli();          // Disable interrupts
    rcN = rcChange;
    rcChange = 0;       // Zero the change counter
    rcT[0] = rcTimes[0];
    rcT[1] = rcTimes[1];
    rcT[2] = rcTimes[2];
    rcT[3] = rcTimes[3];
    sei();          // reenable interrupts

    Serial << "t=" << millis() << " " << rcT[0] << " " << rcT[1]
       << " " << rcT[2] << " " << rcT[3] << " " << rcN << endl;
  }
  sei();            // reenable interrupts
}

The code shown above uses Streaming.h, a contributed library that adds some “syntactic sugar” to Arduino C.  That is, at compile time it converts C++-like << Serial stream operators to Serial.print statements, without increasing code size.  If you don't have Streaming.h installed, either install it via Streaming5.zip from arduiniana.org or manually translate the Serial << ... statement to Serial.print statements.

A sample of the sketch's output on serial monitor:

t=35773 0 0 14196 13456 4
t=35775 0 0 14196 13456 3
t=35778 0 0 14196 5748 4
t=35781 0 0 5244 5748 3
t=35783 0 0 5244 5748 4
t=35785 0 0 5244 5748 3
t=35786 0 0 5244 28 12
t=35788 0 0 3024 28 3
t=35789 0 0 3024 28 4
t=35792 0 0 3024 28 3
t=35796 0 0 3024 6396 4
t=35802 0 0 9316 6396 3
t=35809 0 0 9316 6396 4

In the output above, the two 0's are from A0, A1 being grounded and not changing.  The next two numbers are from the DT and CLK lines of a KY-040 rotary encoder, which toggle alternately to encode step-direction.  They should represent on-times in microseconds, and are always multiples of 4 because micros() reports multiples of 4.

The last number is the number of times the ISR's change-checking loop ran since loop()'s previous print.  An A2 change will show a count of 3 or more, and an A3 change 4 or more.  Cases where times are the same may represent contact bounces shorter than the ISR's service time; ie, several falling edges in a row might be detected, or several rising edges.  A storage scope or logic analyzer probably is necessary for finding out exactly what happens.


Most compact way to power 5V Arduino boards? So I have quite a few ideas for wearable devices using Arduino boards (mainly the Nano and the Micro clones). With that in mind, I want to determine what the best way to power an Arduino is, with compactness in mind (and cost too, of course). One single button cell battery does not supply enough power to the Arduino to power it properly. I can use these 2x button cell battery holders (6v) but they mainly ship only from China and, for some reason, are relatively expensive ($15 for 6 of them).

Does anyone know of a better and cheaper way of powering these Arduino boards, with wear-ability in mind?

Thanks! :)

I made a torch locator which looks like this:

That was powered by a single button cell. The actual processor is an ATtiny85. As you can see it isn't much bigger or heavier than the coin cell.

You can run the Atmega328P (and the ATtiny) at 3V (as from that battery) provided you slow them down to 8 MHz. That is quite easy to achieve, and then you don't need an external crystal as the Atmega328P has an inbuilt oscillator which can drive it at that frequency (as does the ATtiny).

I have a page about power saving which might help you with your design.

A possible alternative is a single LiPo cell (nominally 3.7V) which, if you get a small one, should be quite light.


Tracking Device Using Arduino UNO, GSM and GPS I'm using SIM900A and GY NEO6MV2. I'm supposed to receive device location continuously after sending "Staff" to GSM and will stop receiving the location if I send "Stop" to GSM. This work on Serial monitor but not on my cellphone.

    #include <SoftwareSerial.h>
    #include <TinyGPS.h>

    float flat, flon; // create variable for latitude and longitude object
    int temp=0,i;

    SoftwareSerial mySerial(10, 11); // create gps sensor connection
    TinyGPS gps; // create gps object

    void setup(){
       Serial.begin(9600); // connect serial
       mySerial.begin(9600); // connect gps sensor
       delay(2000);
       Serial.println("AT+CNMI=2,2,0,0,0");
       temp=0;
     }

     void loop()
     {
        while(Serial.available())
        {
           if(Serial.find("Staff"))
           {
              get_gps();
           }
           if(Serial.find("Stop"))
           {
               loop();
            }
         }
      }

     void get_gps() // run over and over
      {
        unsigned long start = millis();

        while (millis() - start < 10000) {
        if (mySerial.available()) {
             char c = mySerial.read();
             if (gps.encode(c)) {
                 gpsdump(gps);;
             }
            }
          }
        }

     void gpsdump(TinyGPS &gps)
     {
         init_sms();
         gps.f_get_position(&flat,&flon);
         Serial.print("Location?\nRight here:\n");
         Serial.print("Google Maps: https://google.com/maps/place//@");
         printFloat(flat, 5); Serial.print(",");
         printFloat(flon, 5); Serial.print('\n');
         Serial.print("Location as metioned above\nTQVM");
         Serial.write(0x1A);
         delay(2000);
       }

      void init_sms()
     {
       Serial.println("AT+CMGF=1");
       delay(400);
       Serial.println("AT+CMGS=\"+60134484868\"");
       delay(400);
     }

    void printFloat(double number, int digits)
    {
     // Handle negative numbers
     if (number < 0.0) {
     Serial.print('-');
     number = -number;
    }

      // Round correctly so that print(1.999, 2) prints as "2.00"
      double rounding = 0.5;
      for (uint8_t i=0; i<digits; ++i)
      rounding /= 10.0;

      number += rounding;

    // Extract the integer part of the number and print it
     unsigned long int_part = (unsigned long)number;
     double remainder = number - (double)int_part;
     Serial.print(int_part);

    // Print the decimal point, but only if there are digits beyond
    if (digits > 0)
    Serial.print(".");

     // Extract digits from the remainder one at a time
     while (digits-- > 0) {
     remainder *= 10.0;
     int toPrint = int(remainder);
     Serial.print(toPrint);
     remainder -= toPrint;
    }
   }

void loop() {
    ....
    loop();
    ....
}

That's an instant death warrant right there. You can kiss your stack goodbye as it crashes mercilessly into your heap. Never ever ever call loop() from anywhere.

Your decision as to whether or not to get the GPS data is completely flawed. It will run the function once when it finds "Staff" and never again (unless it sees "Staff" again on serial). It doesn't keep finding the same thing over and over again unless you keep sending it over and over again.

And come to that - how exactly are you sending "Staff" and "Stop" through GSM? I assume by SMS message, however I see no code there to actively retrieve the SMS messages from the SIM. So you'll never see anything anyway.

You need to completely re-think your whole program methodology:

Look for new SMS messages
If any exist then read one and delete it.
If the message contained "Staff" then enable sending mode. If the message contained "Stop" then disable sending mode.
If sending mode is enabled and enough time has passed since the last sending then get the GPS data and send it.

You notice the sending of the GPS data is separated from the SMS reception. It's not the reception of the SMS that controls the GSM but the "mode" your program is running in. The SMS just controls that mode.

This is a crude form of Finite State Machine.


Using the Logging library, sometimes doesn't exit setup() This has been a hard problem to diagnose, so I hope I'm giving enough info here.  I'm trying to write a program for the Arduino (a lighting controller) using a bit of OO.  There are several classes in my library, and some extend others.  I'm a long-time programmer (mostly Java) but this is my first big Arduino project.

I'm using the Logging library at various points in the main program, as well as the objects, and that's where it get complicated.  Depending on where I put calls to the logging library, or even Serial.print(), it either all works, or what gets sent to the serial port is a bit garbled, and the board never enters loop() (I'm not sure if that means that it's crashing in setup() or not).  This library hasn't been touched in 4 years and there are pending merge requests, so I don't think I'll get answers from the developer.

I have a sneaking suspicion that the root of the problem is that Logging.h ends with instantiating the logger ("Logging Log = Logging();") so multiple instances of the logger may be created and the serial port is being reset several times, possibly at different port speeds.  I thought it was bad form to initialize object, or even have any running code, in a .h file.  Is this a possibility, and do I have any options to fix this?

Are there any good alternatives for printing outputs at different debug levels?

I would hate to have to pass the logger instance in as a parameter to my classes, or have to write setLogger() methods for all my classes.

Thanks.

The constructor (called in a rather weird way) doesn't do anything, so I don't think that is the issue.

Logging.h:

    /*!
     * default Constructor
     */
    Logging(){} ;

Logging.cpp:

 Logging Log = Logging();

You should be calling Log.init(whatever) once in your code (as in the example). Are you doing that?

Please post a Minimal, Complete, and Verifiable example.

Without any posted code, we can only guess at what you are doing.

  I thought it was bad form to initialize object, or even have any running code, in a .h file. Is this a possibility, and do I have any options to fix this?

That is not done in the library you linked to.


Detect if a chair is occupied using Arduino with some sensors I want to detect if a seat is occupied by a person. This is the answer that I found on Stackoverflow.

However, how accurate is the output of 4 suggested sensors? Will the computing of all these 4 sensor values into one boolean recognize a case when, for instance, a box of 40kg is placed on a seat and some person is just slightly "shaking" that seat with a hand? In those cases Arduino should recognize that a seat is not occupied by a person. Will it work with only 4 sensors or is there any better and more accurate solution (maybe some existing library)? I guess that CapSense-Library is not applicable in my case.

As has been mentioned in the comments there's many ways of sensing, each with its own pros and cons.

Sensing the presence of something is actually twofold.  First you need to know if there is something there, and secondly you need to try and identify what it is that's there and if it fits your criteria.

With passive sensors of the type used by Arduinos it all comes down to a matter of probability.

If you have force sensors, you know when something is there, but you can't work out what is there, only that it weighs a certain amount.

Using capacitative sensors you can get an idea about what the something is made of - how much does it affect the capacitance, etc.

Using ultrasound and/or infra-red beams etc you can get an idea of the kind of size of the object that is in the chair.

So combining them all together you can work out the likelihood that it is a human if:

It weighs enough to be a human
It has a suitable dielectric response to be a human
It is big enough to be a human

Of course, there's always the chance that it's just a big dog, or a sack of potatoes.

So it's all a case of improving that probability by adding more sensors of different types, until you are almost certain that it is a human.  You will never be 100% certain, of course.


Connection Problems with GPRS Shield I recently bought a GPRS shield from Seeed Studio but was having issues running the programs described in their documentation.  Here is everything you need to know about my shield:

Documentation for GPRS Shield V2.0

Website to purchase GPRS Shield V2.0

I assumed that there was a connection problem. I used the following code to try to debug my SIM900 and its connections to the sim card and the cellular network:

#include <SoftwareSerial.h>
SoftwareSerial gprsSerial(7,8);

void setup(){
  gprsSerial.begin(19200); // GPRS shield baud rate
  Serial.begin(19200);
  delay(500);
}

void loop(){
  if(Serial.available()) {
    switch(Serial.read()) {
      case '0': testSIM900(); break;
        // AT OK
      case '1': testSIMCARD(); break;
        // +CPIN: READY
        // +CREG: 0,1
      case '2': testNETWORK(); break;
        // +CGATT: 1
    }
  }

  if(gprsSerial.available()) Serial.write(gprsSerial.read());
}

void testSIM900() {
  gprsSerial.println("AT");
  // AT OK
  delay(100);

}

void testSIMCARD() {
  gprsSerial.println("AT+CPIN?");
  // +CPIN: READY
  delay(100);
  gprsSerial.println("AT+CREG?");
  // +CREG: 0,1
  delay(100);
}

void testNETWORK() {
  gprsSerial.println("AT+CGATT?");
  // +CGATT: 1
  delay(100);
}

When I entered 0, 1, and 2 into the serial monitor, I got the following response:

AT

OK
AT+CPIN?

+CPIN: READY

OK
AT+CREG?

+CREG: 1,2

OK

+CREG: 0

+CGREG: 0
AT+CGATT?

+CGATT: 0

OK

What does this tell me about the current state of my shield, sim card, and network connection? Is there anything else I can do to isolate issues?

It seems it can't register on the network, GSM modems are power hungry, are you sure you're powering it up with the external power source (through Vin)? Pretty sure the Arduino isn't enough, but I could be wrong, that's a shield that has those issues in mind.

Also try to see the signal strength using AT+CSQ.


Using multiple HC-SR04: sharing trigger pin and interference between HC-SR04 If I have four HC-SR04 detectors, can they share the same trigger pin on the Arduino?  This would reduce the number of pins needed from eight to five.

Even if they can share the same trigger, maybe this doesn't make sense because the emitted signal from one HC-SR04 will give a false reading to the others.  If this will occur, how much time should the sketch pause before triggering/reading the next HC-SR04?

Thanks.

No, you can't really share the same trigger pin, for the reasons you have already worked out. You can, though, share the same echo pin, since you know which HC-SR04 has been activated by the trigger.

To do that you will need a "wired or" circuit. The simplest method is a diode per ECHO signal and a pull-down resistor:

simulate this circuit – Schematic created using CircuitLab


Can't open "COM1" on Linux with Trinket Pro At work, on a Ubuntu 14.04 system, I can access my Trinket Pro without any difficulty whatsoever.

At home, using either Linux Mint or Ubuntu across two laptops, I can not communicate with the device no matter what I try.

I have the correct board selected, the correct processor, and trying to use USBTiny ISP.

Currently, I'm getting:

avrdude: ser_open(): can't open device "COM1": No such file or directory
An error occurred while uploading the sketch

It's really getting frustrating having to take my devices to work just to upload a sketch, and I've been banging my head for over a week and a half. My UNO R3 boards work without issue on the same laptops.

Here's what dmesg says:

[  863.471315] usb 1-1.1: Product: USBtiny
[  863.471316] usb 1-1.1: Manufacturer: Adafruit
[  876.438778] usb 1-1.1: USB disconnect, device number 12
[  880.921492] usb 2-1: new low-speed USB device number 5 using xhci_hcd
[  881.092152] usb 2-1: New USB device found, idVendor=1781, idProduct=0c9f
[  881.092157] usb 2-1: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[  881.092161] usb 2-1: Product: USBtiny
[  881.092163] usb 2-1: Manufacturer: Adafruit
[ 1004.305143] usb 2-1: USB disconnect, device number 5
[ 1019.935505] usb 2-1: new low-speed USB device number 6 using xhci_hcd
[ 1020.106524] usb 2-1: New USB device found, idVendor=1781, idProduct=0c9f
[ 1020.106530] usb 2-1: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[ 1020.106533] usb 2-1: Product: USBtiny
[ 1020.106536] usb 2-1: Manufacturer: Adafruit

I am running IDE version 1.8.3, with sudo, the exact same way I'm doing at the office.

Can someone please advise on what I'm missing here? Windows is not an option; I haven't used it in many years. I'd just like to figure out what's wrong.

I do have an FTDI connector, but didn't have much luck with it either, and to be honest, don't want to use it as I just want to plug the Trinket in, and upload.

Update: I've tried both USB2 and USB3 ports repeatedly with the same results.

[  881.092161] usb 2-1: Product: USBtiny
[  881.092163] usb 2-1: Manufacturer: Adafruit
[ 1004.305143] usb 2-1: USB disconnect, device number 5
[ 1019.935505] usb 2-1: new low-speed USB device number 6 using xhci_hcd
[ 1020.106524] usb 2-1: New USB device found, idVendor=1781, idProduct=0c9f

The USB Tiny ISP device which this logs shows being connected to your system is not a USB serial device.  Therefore, it will not have any /dev/ttyXXX device associated with it.  Instead it should be used with the -c usbtiny argument to avrdude.

Adafruit documents their products fairly well, and this is no exception.  The Linux section of the user guide is at https://learn.adafruit.com/usbtinyisp/avrdude#for-linux

That guide goes on to explain that you will typically need to create a udev rule to allow an ordinary user account to access the device.  Depending on Linux installation, typical contents might be

SUBSYSTEM=="usb", SYSFS{idVendor}=="1781", SYSFS{idProduct}=="0c9f", GROUP="users", MODE="0666"

or

SUBSYSTEM=="usb", SYSFS{idVendor}=="1781", SYSFS{idProduct}=="0c9f", GROUP="adm", MODE="0666"

The above linked guide will more comprehensively explain how all of this works.

Note that the above pertains to the USB Tiny ISP programmer shown in your dmesg output.  According to the Adafruit page on the Trinket Pro, the Trinket Pro "bootloader looks just like a USBtinyISP" therefore, you would talk to it in the same way as the USB Tiny ISP that your system reports finding, ie, without using a /dev/ttyXXX device, but rather by specifying -c usbtiny in the avrdude command line, or using an Arduino IDE board configuration which does so.

Your error message suggests that avrdude is not being run with the correct command line options.  You may want to turn on verbose mode to see what is being run - it would especially helpful if you did that on both the working and the non-working Linux systems.


Reversed Input Voltage Arduino Mega timeout communication with programmer error On the barrel connector I accidentally reversed the input voltage to an Arduino Mega. The center post received ground while the outer connection received +12DVC, basically I have the Arduino -12VDC. I have since fixed this problem. When I power the Arduino with the USB I am able to program the Arduino without a problem. When I power the Arduino with the +12VDC the program still runs (confirmed by programming the blink sketch). If I have the +12VDC connected and try to program the Arduino then I get the timeout communication error.

Do I just need to re-burn the bootloader? The Arduino's symptoms match those listed here when both cables are connected: Arduino Mega timeout communication with programmer error

Is there anything else I should verify? Or is the Arduino always going to be damaged?

Also as a note I did the same thing to an Arduino Uno (same rail going to both) and the Uno has no problems when both USB and power are connected.

Chances are you have blown up the circuitry that performs the switching between barrel jack and USB power sources.  As a result the USB interface chip isn't getting power when it should.

In short: "It's dead, Jim!"


How to control Adruino through Internet I want to control my Adruino through Internet without Ethernet or wifi shield. So what are the ways I can do?

Guess you need to use a pc, and a program to receive commands and send them along to the arduino by serial.


Power problems stacked Arduino shields I have a weird problem. I am currently building a BB-8. Therefore, I am using an Arduino Uno. On top, I have stacked an Adafruit Motor Shield v2.3 and, again, on top of this, I have stacked the Sparkfun USB Host Shield. The Arduino is powered by a 9V-Block battery, the motors are powered separately by two 18650 Li-Ion batteries. To control the two Pololu motors, which have a stall current of 1.6 amps each, I use a Xbox 360 wireless controller, where the receiver is connected to the USB Host Shield.

Now to my problem. Every seems to work fine, until i cover everything with a styrofoam hemisphere. Yes, you've read right. If that happens, the controller signals is lost and does not connect again, unless I restart the Arduino. I have uploaded a small video on youtube, where you can see the problem.

I guess, this is a power problem, since this issue does not occur, when I connect the Xbox receiver to my Mac. Has anyone an idea, how to solve this problem?

I already tried another power source. And the USB host shield should give enough power, since the specs are saying, that 500 mA is no problem, and hit is exactly the USB 2.0 spec. The combination of the shield shouldn't be a problem, too. I carefully chose this shields, because the motor shield is just using the pins A4 and A5, the USB host shield is using some of the digital pins, so I think there is no interference.

Thank you for your help.

EDIT
I have tested it a bit more now and i think i can reduce the probable reasons. First, i tried some other power supplies, from AA batteries on the VIN pin to external power adaptors. Next, i tried other xbox receivers and controllers. I also tried a playstation 3 controller with a Bluetooth dongle. Nothing solved the problem. I also covered the Arduino with other things than styrofoam, like a garbage can, cardboard and some metal box. This worked, so the problem was only with styrofoam. Now i haven't covered the Arduino, but i slowly got closer. About 20 cm from the Arduino, it stopped working. My clue: static electricity. Do you think this can be a problem? And if yes, how can i solve this?

Those 9v batteries are not known for their ability to supply current. Their best uses are long-term powering of low-current standby devices like smoke detectors. I'd first try replacing it with 4 double- or triple-A cells, whatever you can scrounge up for a quick test. My guess is when you cover the robot the Xbox receiver's current demand increases just enough to crash or reset something. A-cells may supply enough more current without the voltage sagging.


How to obtain the type of DHT sensor I made a simple temperature controller on DHT11.
I want it to work with DHT22 as well having the same code.

However, I can’t find a way how to get known what type of sensor is installed.
Is there a way?

You can use another library for DHT: https://github.com/markruys/arduino-DHT
Although, the library is quite old, it works fine and has auto-detection feature.


nodemcu esp8266 does not boot up when 5V pin is connected as a VIN source Whenever I boot up the esp8266 or flash code via usb ,I have to remove vin pin otherwise it does not boot up.

If I remove vin pin then flash and boot up happens and then i am able connect vin with 5 V relay.(using VIN to power up relay) .

I dont understand what it has to do with VIN pin.please suggest.

I am using below pins for eight devices

//relay pin setup for funct
int relayOne = 5;
int relayTwo = 4;
int relayThree = 0;
int relayFour = 2;
int relayFive = 14;
int relaySix = 12;
int relaySeven = 13;
int relayEight = 15;

IO pins 0, 2 and 15 are boot configuration pins. 15 must be LOW at boot, 2 must not be LOW at boot and 0 determines the flashing mode. For normal run pin 0 must be HIGH. The NodeMcu board has necessary pull-up and pull-down circuits.

You can connect to pins 0, 2 and 15 only devices which don't change the boot state.


Esp8266 not responding to GET request from Android app created using MIT App Inventor I hope I am posting this question in the right section.
I am making a Smart Home Project for my college semester finals. I am using an Atmega328p microcontroller along with an ESP8266 (Esp 01). The Atmega328p controls all the sensors and actuators and sends the data to Esp01 via serial communication.

I have created a web server on the Esp01 which I plan to access by creating an app using MIT App Inventor. My GET request is of the format "http://192.168.43.42/4" where the digit at the end is data I want to send to the server and the response I get from the server is of the format "12&0&34.8" where the '&' is used to separate different values.

My problem is , when I access the server from Chrome in my laptop I get the desired response but when I access it using the App , I get an error "Error 1101 :Cannot find the specified URL". The Esp01 is connecting to a hotspot from my phone and I have checked the IP assigned to the Esp01 to ensure my GET request is correct.

The code for Esp01 in Arduino IDE is here : https://gist.github.com/TheMagicSmoke/467d6227d670697464038056e22f302d

The blocks for the app made in App Inventor is below:

The GET request URL when entered from Chrome in laptop returns a blank page at first but upon refreshing Chrome I get the desired response I told earlier. And in the app , I have used a timer which queries the server with the same GET request every 2 seconds. But when I open the App the error keeps on popping up. Please suggest me a solution, I have googled this without any success.

I have found out the solution to this problem. The code that I had written in the Arduino IDE for the Esp8266 was not correct for handling the GET request.  It only accepted data as a simple Web Server and not as a HTTP server. I am posting the modified code below .

https://gist.github.com/TheMagicSmoke/adaae1e4d92f258c88184c8690e68f08


MPU6050 doesn't work I am trying to do a self-balancing bot as a school project, but I got stuck with the MPU6050.

I tried using the code by Jeff Rowberg (MPU_6050_raw) but it's reading only zeros.

I tried the MPU_6050_DMP and got stuck at "initializing DMP..." and no reading is shown.

I tried other code, but same thing happens, either reading zeros or getting stuck at "initializing DMP..".

And how can I make sure that the chip isn't broken?

The MPU-6050 is a 3.3V chip. When you are using a 5V Arduino board, you should take care that you don't put current into the SDA and SCL pins of the MPU-6050.

Start with a i2c scanner.
This one: Arduino Playground I2C scanner
Or this one: Nick Gammon I2C scanner
If the I2C scanner halts, then there is a hardware problem with the I2C bus. It might be a shortcut of SDA or SCL to GND, or the MPU-6050 module is not powered.

If the I2C scanner is working, then you know the address (0x68 or 0x69). With that address you can try the Short example sketch to read data from the chip.

If that is working, then you can try the Jeff Rowberg library.


What software is available for use with AVRISP and USBASP on ATMega48, 328, 2560? What software is available for use with AVRISP and USBASP on ATMega328, 2560 for read/write fuse, flash and EEPROM for UNO, Pro Mini and Mega2560 board?

(a fact question not opinion) Which software did you use?

Did it work straight forward (like the software did all the needed 'auto select')?

Does it need human selection for options, etc. on the above 3 boards?

Do I need WinAVR installed before able to use the 'ISP software'?

Almost everyone uses either AVRDUDE (directly or indirectly, e.g. via the Arduino IDE) or the upload capability in Atmel Studio. I cannot speak for AS, but AVRDUDE does require options to tell it which programmer and device to use. WinAVR includes AVRDUDE, but is not strictly required as Win32 downloads are available at the AVRDUDE site.


Arduino IDE, Underlying Code and Libraries I'm trying to better understand what is going on behind the Arduino IDE. First off I am no expert in C or writing firmware to boards but do have experience in real development.

I see currently the Arduino IDE is one big vast library we first select our board.
What I don't understand is where are our header files? The source files for the board you select?

Not only that we use a number of functions already detected within the IDE where are these located also is any of this code editable?

I had a look through the Arduino directory and most of this stuff looks like its Java I was hoping for C files. Thanks for any links, help or info anyone can give.

Just check the source code. Specifically look at Arduino.h, main.cpp and wiring*.

These files should also be present in the Arduino application folder somewhere, but you'll have to go through quite a few subfolders to find them.

The different boards have different .h file that will specify the pin-numbers and other chip specific data.

The "auto detect" functionality is done by keywords.txt files. At least for libraries. That way if you install a new library with keywords.txt file, the library functions-names are recognized.

The processes of taking all these files, and the users code, and compile it all whole story on it's own.


Leonardo (32u4): Timer0 problems with CTC mode I want to use timer 0 to generate a rectangular signal on OC0A (D11) without the use of Arduino specific functions (that use timers for themselves). When I toggle D11 manually using a loop, I hear a sound in the connected piezo, but with my sample code, I don't hear something:

#define ALARM_PIN 11

void setup() {
  digitalWrite(ALARM_PIN, LOW);
  pinMode(ALARM_PIN, OUTPUT);
  noInterrupts();

  OCR0A = 60;
  // Toggle OC0A on compare match
  TCCR0A = (0 << COM0A1)
         | (1 << COM0A0)
  // CTC mode
         | (1 << WGM01)
         | (0 << WGM00);
  // prescaler = 256
  TCCR0B = (0 << WGM02)
         | (1 << CS02);
}

void loop() {
}

Any idea, what could be wrong?

Update

I've played with it a little bit more:

#define LED_PIN 9

void setup() {
  pinMode(LED_PIN, OUTPUT);
  TCCR0B = (1 << CS02);
}

void loop() {
  digitalWrite(LED_PIN, TCNT0 > 250);
}

This causes my LED to light very dim, so the timer is running up to 255. But as soon as I set TCCR0A, nothing is lighting up:

#define LED_PIN 9

void setup() {
  pinMode(LED_PIN, OUTPUT);
  OCR0A = 60;
  TCCR0A = (1 << WGM01);
  TCCR0B = (1 << CS02);
}

void loop() {
  digitalWrite(LED_PIN, TCNT0 > 0);
}

You should re-enable interrupts after you finish setting up. Use either

interrupts();

or

sei();

If you want to don't want to use the arduino specific commands. Even if the code does not need interrupts, background code does use them.

Timer 0 is used in arduino for some basic "house keeping" function like keeping time. I'm not sure if that could be part of your problem. you could try using a different timer.


SIM808 module restarting repeatedly I have bought SIM808 module, everything working fine. All AT commands are giving expected response, i'm accessing it through hyperterminal. My problem is that whenever i make or receive a call or SMS , GSM gets restarting.(I can able to make/receive call, getting ring/alert for small period of time and then interrupt). But there is no Under or Lower voltage power down or warning.
I have tried with DC power supply of 5V/500mA , 5V/1A and 5V/2A.  What might be the reason ? Please help.
extra info : It has one LM2576S voltage regulator in-built.

Check the datasheet and I think you will find you need 3 amps peak.  It requires this peak current when you make a call or send a text/sms.

Use a 5A power supply and that should solve the problem.

I have never tried it but "super capacitors" might work, providing the extra power when its needed, it depends how long you need the 3A for.


Arduino over a Network I am new to arduino programming. I want to sense temperature and send it to a server in my college. I am using Arduino Uno R3 board which has ATmega 328P micro-controller. I am able to get serial output on my PC but is there a way in which I can send temperature data to the server in a packet format using Arduino Programmer and not using Ethernet Shield ? Please answer in a less complex way.

Without an ethernet shield or some kind of other internet connectivity shield/circuitry you cannot communicate directly with the internet through the arduino. However, if having a computer as the internet communicator isn't a problem you could try a setup like:

arduino->serial (usb)->processing->internet

This way you create the internet packet in processing using the temperature information received through serial from arduino.

see also https://processing.org/


Bluetooth a pushbutton from one arduino to another to turn on a LED For a major project at school i need to get a bluetooth module to be able to communicate between two  HC-05 modules as a master and slave. They need to be able to press a pushbutton on the slave and it lights up a LED on the master.
I have been able to get the two hc-05's to connect to each other but i cant find a code and wiring that will work for what i need to do.
any help will be appreciated. Thanks

So, you have done the hard part and now need the easy bit :)

Firstly you need a button (failing that touching two wire together will just about do).  There are loads of quick tutorials on the web, here is one https://www.arduino.cc/en/Tutorial/Button.  They will end up with you having a pin that goes high or low when the button is pressed, you can either poll/loop to detect the press or go posh and use interrupts (leave that for later).  When the pin detects the press you need to send some data via your HC05 link to the master, something like 'ON' or 1, who cares so long as the master understands it.  And when it disconnects you need to send a off or 0 message (Remember the number 1 and the character '1' are not the same thing, so make sure you know what you are sending).

When the master receives the command it will execute a bit of code that will send a pin high (lets say pin 7).  Connected to pin 7 will be the +ve side of a LED, the -ve leg of the led will be connected to a resistor of 200-250 ohms and the other end of the resistor will be connected to ground.  Then when pin7 goes high it will light the resistor.

simulate this circuit – Schematic created using CircuitLab

As always you probably will need to break it down to test it, have a little app that toggles pin 7 high for 2 seconds and low for two seconds, etc (just like blink).

There is a phenomenon called 'bouncing' which is where the useless human finger presses a switch and doesn't instantly create a perfect connection and perfect disconnection.  This might make the slave send 101010101010101 when you just expect 1, you can either debounce using software or hardware, but only worry about that if you have a good quality switch :)


Keyboard Control Not Working As Intended I'm trying to control a single motor.

If I press 'a', then motor 1 should turn to 0, if I press 's', then motor 1 should turn to 180

#include <Servo.h>

char key = 0;
const unsigned int BAUD_RATE = 9600;

Servo Servo_0;

void setup()
{

  Servo_0.attach(0);
  Servo_0.write(0);

  Serial.begin(BAUD_RATE);

 // Serial.println("      Arduino Serial Servo Control");
 // Serial.println("Press < or > to move, spacebar to center");
 // Serial.println();

}

/*
a - 97
s - 115
d - 100
f - 102
*/

void loop() {

  if(Serial.available()>0)
  {
      key = Serial.read();
      Serial.print("I received: ");
      Serial.println(key, DEC);

     if(key == byte(97))
     {

       Serial.print("Turning Motor 1 to 0 deg");
       Servo_0.write(0);

     }
     else if(key==byte(115))
     {
       Serial.print("Turning Motor 1 to 180 deg");
       Servo_0.write(180);

     }

     delay(1000);
}

But what is happening is that the motors are barely turning after I enter the key onto the Arduino monitor interface. Can anyone diagnose as to what might be happening?

The problem I see is that your servo is attached to pin 0.

Pins 0 and 1 are used by arduino unos and megas for serial communication, so you can't output to a motor and send/receive serial at the same time. Try moving the servo to pin 3 and see what happens.

In response to your comment, any character sent from any terminal (or other piece of hardware) will work; you do not need to use Processing to communicate with an arduino.


Engine Speed Control Observation I am using an Arduino Mega to control the speed of an internal combustion engine.

The speed is sensed via a Variable Reluctance Sensor (VRS) on the crankshaft. This signal is then converted into a 5V square wave which is feed into Interupt 2 (Pin 21) on the Arduino.

The flywheel of the engine, onto which the VRS is sensing has one tooth. Therefore one square wave blip (from 5v to 0V) as it is passing it and then back up to 5v. The interupt that this is attached to increases a counter by 1. The time taken for the counter to reach 20 is recorded. I want to use this speed reading value in a PID algorithm which then in turn actuates a servo.

This methodology was sucessfully used in a very similar engine with a 22 toothed flywheel but is not working on this engine with 1 tooth.

The problem is the speed reading - the values that I am recording for the time taken for 20 revs ( in micro seconds), and displayed on the serial terminal is wrong and I do not know why. The numbers printed are all mulitples of one another e.g. 440960,551200,661440,771680 which all divide into one another with an even fraction. The correct reading here is 661440, this has been verified with observation of the square wave input through and oscilloscope.

I cannot find why!

I have attached the code here

Your methodology there is somewhat flawed. Not only will you never see that Counter1 >= 20 (since you immediately set it to 0 before returning the count), but if you never get a pulse (engine is stalled) you'll never reach 20 pulses anyway.

A better method is to reverse everything and instead of timing how long it takes to get 20 pulses, count the number of pulses you get in a pre-defined time period.

Your interrupt remains the same, counting each pulse as it arrives, but you then sit and watch the clock (using millis()) and when a certain (to be decided by you) time has elapsed (the sample time) you record the pulse count and reset it to 0. You then have a number of rotations per time period.

If you set that time period to be 1 second (the simplest) then you immediately have the number of rotations per second.

void loop() {
    static uint32_t ts = millis();
    uint32_t pulses;

    if (millis() - ts >= 1000) {
        ts += 1000;
        uint8_t sr = SREG;
        noInterrupts();
        pulses = Counter1;
        Counter1 = 0;
        SREG = sr;
        Serial.print(pulses);
        Serial.println(" revolutions per second");
    }
}

Decreasing the sample time means you can respond faster, but you are working with smaller numbers and hence less accuracy. For instance, setting it to 100ms instead of 1 second you need to multiply your count by 10 to get the current pulses per second. It all depends on how fast your engine runs as to what a good sample time would be.


Wemos D1 & Relay shield For one of my hobby projects I would like to use:

Wemos D1 mini pro (schematic)
Wemos D1 Relay Shield (schematic)

to control the 24V (19W) mist maker.

My current wiring is this:

As you can see the both grounds (12V and 5V) are attached to the com connector of the power supply.

I wonder whether grounds should be decoupled (for whatever reason) - i.e. to use separate power supplies? If the above wiring is OK I would really like to know in which circumstances (if any) a separate power supplies would be needed.

Thanks for all your answers in advance.

That grounding scheme looks right since the Load ground is coupled back to the supply separately from the logic ground.

The only reason you would separate supplies would be to isolate them for safety or other reasons. For example, if the load side was a large or ac voltage.

Isolation requirements vary with application so it is hard to be more specific than that here.


M0 pro: SPI communication, code works on Uno, but not in M0. Using ICSP port I am trying to establish a communication between a sensor and a M0 -pro using SPI. The code :

    #include <SPI.h>

    unsigned int result  = 0;
    void readAngle();

    void setup() {
      Serial.begin(9600);
      SPI.setBitOrder(MSBFIRST);
      SPI.setClockDivider(SPI_CLOCK_DIV8); //sets the clock speed for data transfer, slowed down 8 times
      SPI.setDataMode (SPI_MODE1);

      digitalWrite(11,HIGH);
      pinMode(11,OUTPUT);

      SPI.begin();
      SerialUSB.println("First Try");
}

    void loop() {
      readAngle();
      SerialUSB.println(result);
      delay(500);

}

    void readAngle(){
        digitalWrite(11,LOW); //Turn SS on, start communication
        result = SPI.transfer16(0xFFFF); // the read command and the response received
        result = (result << 2) >> 2; // get rid of the last 2 bits, error(14) + parity(15)
        digitalWrite(11,HIGH); //Turn SS of

}

The code works perfectly with an UNO, but with M0, it event doesnt print the first SerialUSB.println("First Try");. The moment i erase the lines that have SPI commands in it, the serial monitor starts working again. As i said in the titel i am using the ICSP port on M0. I use the native usb port to programm.

I think i am missing something very basic. I checked many different forum posts, but there is no indication of M0 requiring other SPI commands. Any help is much appriciated.

PS: i didnt go into detail with the sensor and its datasheet because since it works fine with uno, the cause of the problem should be it.

Which version of the Arduino IDE are you using ? If its an older one, try to get the latest one, sometimes that solves issues like the one you have.


RF24L01+ VER01 with 10 pins How can I connect this little ship to my Arduino? I can find alot of tutorials how to do it so, but all I find is 8 pins, mine includes 10 pins, and from what I could of understand from searching me myself, that there is 2 pins of VCC and 2 GRN pins.

So I would like to know how to connect this? Not necesserly Arduino, but can someone help me with the pins names at least so I can identify them.
Thanks.

There are some 10pin adapter boards floating around. See e.g.
nrf24l01 (8pin) + adapter board (10pin) oops?

Their pinout looks to be the following.


Is there any reason not to solder power leads to the lugs for the power in socket on the reverse side of a mega 2560 rev 3 board? I have a very tight space for a project that requires a mega board , the "power in" plug takes it over the space available. Are there safety or other concerns soldering to the lugs for the "power in" socket on the reverse of a mega 2560 rev 3 board board? the board is fitted with an elctrofreaks TFT LCD MEGA SHIELD v2.2 and a TFT_320QVT LCD screen. (the elctrofreaks mega shield uses vin pin)  1 other PWM  pin is used  and an esP8266 board on a uart channel The power  is from a regulated power supply. If  I do this, am I correct that the regulator and polyfuse will still be used?

Soldering to the underside of the connector is exactly the same as plugging something in to the connector.

Yes the regulator will be used.

No the polyfuse will not be used - that is in the USB power circuit not the barrel jack power circuit.


TinkerCAD switch seems to be not working (always closed) I am using TinkerCAD to simulate the functionality of a slide switch. Please comment if you think this question is off-topic.

/*
  LiquidCrystal Library - Hello World

 Demonstrates the use a 16x2 LCD display.  The LiquidCrystal
 library works with all LCD displays that are compatible with the
 Hitachi HD44780 driver. There are many of them out there, and you
 can usually tell them by the 16-pin interface.

 This sketch prints "Hello World!" to the LCD
 and shows the time.

  The circuit:
 * LCD RS pin to digital pin 12
 * LCD Enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4
 * LCD D6 pin to digital pin 3
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * LCD VSS pin to ground
 * LCD VCC pin to 5V
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)

 Library originally added 18 Apr 2008
 by David A. Mellis
 library modified 5 Jul 2009
 by Limor Fried (http://www.ladyada.net)
 example added 9 Jul 2009
 by Tom Igoe
 modified 22 Nov 2010
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/LiquidCrystal
 */
#include <LiquidCrystal.h>

const byte pin8 = 8;

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  Serial.begin(9600);      // open the serial port at 9600 bps:
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Welcome.");
}

void loop() {
  byte val = digitalRead(pin8);
  Serial.println(val);
  if(val == HIGH)
  {
    lcd.setCursor(0, 1);
    lcd.print("Switch on right.");
  }
  else
  {
    lcd.setCursor(0, 1);
    lcd.print("Switch on left.");
  }
}

The serial monitor and the output of the LCD screen are showing the slide switch to always be on the right side (not creating an open circuit when the switch is on the left side).

As seen in the picture, the switch is on the left. And the code, I think, is correct. So it should display, "Switch on left." This is because pin8 is low (not connected to 3.3V).

So I'm very confused. The switch appears to be shorting all three rails to which it's connected. When the switch is removed, that part becomes open; pin8 is low.

As  Sener said, "use a pull-down resistor (10K) from pin8 to GND."

And in case anyone notices, yes, I'm aware of clear().

TinkerCAD must be assuming a floating input reads high instead of an intrinsically floating ground. The most simple solution is adding pinMode(pin8, INPUT_PULLUP); to the setup() function. Then, tie the opposite (than with a resistor) side of the switch to ground: Modified circuit TinkerCAD simulation.


How do I resolve "avrdude: stk500_recv(): programmer is not responding"? Whenever I try to program my Arduino UNO Rev.3, I'm seeing the following error

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00

When I plug this in, I do see a power light. There are no cables whatsoever connected other than the USB. I have another Arduino UNO which works fine when I upload the sketch (I'm using the basic blink sketch). How do I resolve this? What kind of problem can it be?

After trying numerous suggestions, 2 different boards, 3 different cables on a WinXP and a Win7 machine, I finally got things working by going to "Tools -> Processors -> ATmega 328P Old Bootloader"


Does direct port access interfere with PWM? I think I've scoured the SE for questions about PWM, and fast digitalWrite etc, but I didn't see this point addressed.

I need to use direct writes to some digital pins. Some of the pins on the port are using analogWrite/PWM, though not the pins I'm accessing digitally.

In the digitalWrite function the Arduino core checks to see if PWM is in use and disables it if a digital write is attempted. Since the pins here are isolated -- no digital writes to PWM pins -- is this a needed step?

The reason I ask is that when accessing a port directly, as in PORTD |= (PORTD & mask) | somebit, you are in fact writing to the pins being used for PWM, you just aren't writing changed bits.

Am I overthinking this? Is it 'PWM-safe' to use direct port outputs on the neighbor pins?

A timer interrupt will be periodically toggling the PWM bit and might do so between your port read and port write.

The easy solution is to turn off interrupts during the read/modify/write portion of your port update sequence. This could cause a stretched PWM cycle. If you don't turn it off, you'd just glitch the PWM - creating an extra, short cycle. Which one is worse for your PWM recipient?

A better solution might be to to watch the port for the PWM bit to change, then jump in right afterward and make your port update. You could do his in either a blocking or a non-blocking manner.

Update:

  Watching the PWM bits seems as if it would be fairly slow, which
  somewhat defeats the purpose of the direct port writes.

Yes, it's less than ideal. There's a tradeoff here. Can your PWM consumer tolerate the potential occasional glitch, instead?

To be complete, there are a number of motivations to use direct I/O:

Smaller code;
Less I/O skew with multiple I/Os, or zero skew if the I/Os are in the same port;
Less execution time on a time-critical path;
Precise output timing;

among others. Those software solutions won't help much in any of those cases.

Can you reassign your output to another pin on a different port, avoiding the whole problem? That might be better than any of the "solutions". Adding hardware might accomplish the same thing - perhaps moving just the PWM to an ATtiny, for example.

Update 2:

  This seems so baked into the structure of the Arduino... does
  digitalWrite() itself actually overcome this?

It "addresses" it - overcomes it? As is so often the case, "that depends".

Here is the the source-code to digitalWrite() from: /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino /wiring_digital.c (on a Mac; the top-level folder or two will be different on Windows):

void digitalWrite(uint8_t pin, uint8_t val)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);
    volatile uint8_t *out;

    if (port == NOT_A_PIN) return;

    // If the pin that support PWM output, we need to turn it off
    // before doing a digital write.
    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    out = portOutputRegister(port);

    uint8_t oldSREG = SREG;
    cli();

    if (val == LOW) {
        *out &= ~bit;
    } else {
        *out |= bit;
    }

    SREG = oldSREG;
}

Notice that the interrupts are saved and restored around the read/modify/write of the port register. So digitalWrite() already addresses the possibility. This method will stretch one phase of an occasional PWM pulse by a few microseconds.

Alternatively, ignoring the possibility of a collision and having one occur, seems more severe: the pulse could be begun or ended prematurely. This occurrence will take longer - the rest of the disturbed phase - to get back in sync.

So the criterion for how to manage x becomes "Which way has the lesser - or more tolerable - consequence for your PWM consumer?"


Arduino - ServoMotor Control and SoftwareSerial My two arduino communicating serially with XBee. The receiver arduino also controls the servo motor. Servo works stably when there is no xBee connection. But when Arduino's serial communication, there is a problem in the operation of the servo motor. Servo motor stuttering while rotate, so stuttering occurs.
Can you help me?
My Coordinator Code:
#include <SoftwareSerial.h>
#define xBeeRxPin 10
#define xBeeTxPin 9
int deger3;
int deger4;
String d1,d2,d3;
SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);

void setup() {
  Serial.begin(38400);
  xBeeSerial.begin(38400);
}void loop() {

  deger3 = analogRead(A0);
  deger4 = analogRead(A2);

  String deger5 =  (String)deger3 + ";" + (String)deger4 ;

  xBeeSerial.println(deger5);

  delay(50);
}

My Receiver Code:
#include <SoftwareSerial.h>
#include <Servo.h>
#define xBeeRxPin 10
#define xBeeTxPin 9
SoftwareSerial xBeeSerial(xBeeRxPin, xBeeTxPin);
String d1,d2,d3;

const int trigPin = 4;
const int echoPin = 3;
long duration;
int distance;
Servo myServo;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  xBeeSerial.begin(38400);
  Serial.begin(38400);
  myServo.attach(11);
}
void loop() {
  for(int i=15;i<=165;i++){
    myServo.write(i);
     delay(10);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, 11200);
    distance= duration*0.034/2;

    if(xBeeSerial.available()>0){
      d1=xBeeSerial.readString();
    }
  }

  for(int i=165;i>15;i--){
    myServo.write(i);
     delay(10);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, 11200);
    distance= duration*0.034/2;

    if(xBeeSerial.available()>0){
      d1=xBeeSerial.readString();
  }
 }
}

When SoftwareSerial enters an interrupt each time it receives a character and busy-waits (delays) to time in each data sample as the bits in the character come in.  No other interrupt service routines can run while this is happening.  It also turns off interrupts when it sends.
The servo library for the AVR uses timer interrupts to generate the servo position signals.
When characters are being received, SoftwareSerial will interfere with the generation of the servo position signal because only one interrupt service routine can run at a time.
You may be able to mitigate the problem adding significant delay between characters sent, reducing the total number of characters sent.  This would limit the interference and give servo time to get back to its correct position from however far it managed to deviate over the course of an inbound serial character.
There are also alternative libraries that use the AVR's Input Capture feature on an ICP pin to do some of the work of serial in hardware, and that may work for you.  Here's one example library.
@ocrdu has rightly prompted me to add that there are servo libraries that will do the servo signal generation in hardware.


Bluetooth Modules not communicating correctly I plug in BT rx to digital 11, BT tx to digital 10 and then 5v and ground from the HC-05 to the arduino. I then upload this code to the HC-05 that is set as a master.

#include <SoftwareSerial.h>

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

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

void loop() { // run over and over
  Serial.println(mySerial.read());
  delay(2000);
}

I then upload this code to the arduino with the HC-05 that is set as a slave:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX , TX

void setup() {
  // put your setup code here, to run once:
  mySerial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  mySerial.write("100");
  delay(2000);
}

The issue is that I never receive "100" on the serial monitor, I only ever receive 49 and occasionally 48. When I changed it from "100" to "10" same thing happened. Any help would be appreciated.

SoftwareSerial.read() returns a single character as an integer. When you print an integer the print() functions convert it to a human readable format.

You want to covert (cast) the output of read() to the char type. Either:

void loop() {
  char c;
  c = mySerial.read(); // store the result in a temporary variable c
  Serial.println(c);
  delay(2000);
}

or

void loop() {
  Serial.println((char)mySerial.read()); // cast the type to char befor printing.
  delay(2000);
}

However since only one character at a time is being read your output will be one character per line (assuming no data loss due to the delay):

1
0
0


Qduino Mini bricked? So I have been experimenting with keyboard inputs and I think I may have accidentally put a loop in my code that never actually ends the keyboard input thus not allowing me to upload any sketches to fix the problem.

Here is the error code I got when I tried to upload a blank into the qduino:

Arduino: 1.8.1 (Windows Store 1.8.1.0) (Windows 10), Board: "Qduino Mini"

Build options changed, rebuilding all
Sketch uses 4136 bytes (14%) of program storage space. Maximum is 28672 bytes.
Global variables use 148 bytes (5%) of dynamic memory, leaving 2412 bytes for local variables. Maximum is 2560 bytes.
An error occurred while uploading the sketch
processing.app.SerialException: Error opening serial port 'COM11'.
    at processing.app.Serial.<init>(Serial.java:125)
    at processing.app.Serial.<init>(Serial.java:66)
    at processing.app.SerialMonitor$3.<init>(SerialMonitor.java:93)
    at processing.app.SerialMonitor.open(SerialMonitor.java:93)
    at processing.app.AbstractMonitor.resume(AbstractMonitor.java:110)
    at processing.app.Editor.resumeOrCloseSerialMonitor(Editor.java:2240)
    at processing.app.Editor.access$2400(Editor.java:77)
    at processing.app.Editor$DefaultExportAppHandler.run(Editor.java:2315)
    at java.lang.Thread.run(Thread.java:745)
Caused by: jssc.SerialPortException: Port name - COM11; Method name - openPort(); Exception type - Port busy.
    at jssc.SerialPort.openPort(SerialPort.java:164)
    at processing.app.Serial.<init>(Serial.java:114)
    ... 8 more
Error opening serial port 'COM11'.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Ok strange, just after posting this the qduino decided to flash a different light on me so I try to upload again and it works... So apperantly just by keeping the qduino connected for some time it will start to work again...


Interrupt on Analog Port - ESP8266 w/ Arduino I'm trying to implement interrupts in my program. It essentially is constantly reading a photo-resistor and if it exceeds a certain threshold, we should send an update to our database. I'm struggling to understand how to do interrupts on a analog pin. I've tried reading this but honestly, it doesn't make much sense. Could anyone give me some advice? Here's out code.

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  // Initally send out false state
  sendState("18:FE:34:F4:D0:AF", false, false);
}

void loop() {

  if(analogRead(A0) < 20) {
    sendState("18:FE:34:F4:D0:AF", false, true);
    lastState = true;
    Serial.println("Waiting....");
    delay(15000);
  } else if(lastState == true){
    sendState("18:FE:34:F4:D0:AF", false, false);
    lastState = false;
  }

}

void sendState(String address, boolean lights, boolean occupied) {

  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  String lightsStr = (lights) ? "true" : "false";
  String occupiedStr = (occupied) ? "true" : "false";
  String json = "{\"MACAddress\":\"" + address + "\", \"occupied\":" + occupiedStr + "}";

  String postData;
  postData += "POST /sensor HTTP/1.0 \r\n";
  postData += "X-Parse-REST-API-Key: " + API_KEY + "\r\n";
  postData += "Content-Type: application/json \r\n";
  postData += "Host: " + String(host) + " \r\n";
  postData += "Content-Length: " + String(json.length()) + "\r\n\r\n";
  postData += json;

  // Send the postdata to the server.
  client.print(postData);

  delay(1000);

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  Serial.println();
  Serial.println("Closing connection!");
}

Interrupts are a tricky concept to get, you have to be mindful of so many things (in bigger projects).

Have a quick look on youtube for some tutorials, there are a heap out there.

Having said all that, your code above isn't using interrupts at all. And you have these big delays, does the code work as published?

I would suggest you rework the code into more of a state machine and have a single loop. ditch all the delays (except for your setup, that's fine) and go along the lines of:

setup

set a variable for current timer value and have a constant defined for your update interval

loop

read sensor (consider constantly reading, or reading it more often than the information is sent, and average it out)
anything on the serial port?

go read it

check timer against old timer and interval
interval exceeded

send averaged value

using interrupts

You could use interrupts but the thing to consider is that they can be run AT ANY TIME. your code must be interrupt-able which whilst isn't too hard, needs special consideration in relation to delays, reading 16bit values, not having delays in the interrupt, status register changes, a whole host of others.

There are two types of interrupt, those that are driven by a change in input and those that are time based. You don't really want the change in state on this one because you would normally want to monitor it constantly anyway, but it is certainly doable.

In both time based and external input, you would have the interrupt set a flag that gets acted upon in your main loop.

sorry for not providing more info at this time, screaming kids :(


Time delay without using delay() and millis() I am designing an industrial control panel using arduino. I have to use time delays as long as 10 seconds and since using delay() makes a halt in the controller I tried using millis(). But it is complicated and it will work only for 50 days. I want the system to work continuously without any maintenance and I need to control as many as 6 relays. So, I need a better solution (hardware or software based) to tackle this problem. How can I do this?

You misunderstand the 50 day thing. Yes it rolls over after 50 days but that doesn't mean it stops working. As long as you program your comparisons correctly (something people often don't do in online examples) then all it means is the maximum delay you can have is 50 days.


Saving a value with a click I have a rotary encoder and 2 buttons to a. Store the encoder value b. Reset the encoder value to 0. The reset buttons work fine the issue is with the set/store button. Where the value changes without pressing the button as well. Any help is appreciated.
int encoderPin1 = 2;
int encoderPin2 = 3;

volatile int lastEncoded = 0;
volatile double encoderValue = 0;
long lastencoderValue = 0;

int lastMSB = 0;
int lastLSB = 0;

// buttons
int resetPin = 43;
int settPin = 22;
int val = 0;
int val2 = 0;

//reset-set
double setValue = 0.0;
double resetValue = 0.0;

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

  pinMode(encoderPin1, INPUT);
  pinMode(encoderPin2, INPUT);

  digitalWrite(encoderPin1, HIGH);
  digitalWrite(encoderPin2, HIGH);

  attachInterrupt(0, updateEncoder, CHANGE);
  attachInterrupt(1, updateEncoder, CHANGE);

  //buttons
  pinMode(resetPin, INPUT);
  pinMode(settPin, INPUT);

  pinMode(LED_BUILTIN, OUTPUT);

}
void loop(){
  //Serial.println(encoderValue); //print
  delay(1000);

  //
val = digitalRead(settPin);
if (val == HIGH){
  set();
  digitalWrite(LED_BUILTIN, HIGH);
}

/*val2 = digitalRead(resetPin);
if (val2 == HIGH){
  //reset
  encoderValue = resetValue;
  Serial.println(encoderValue);
  Serial.print("reset");
  delay(100);
}*/

}

void set(){
  //set the value
  setValue = encoderValue;
  Serial.println(setValue);
  Serial.print("setValue");
  delay(100);
}

 void updateEncoder(){
  int MSB = digitalRead(encoderPin1);
  int LSB = digitalRead(encoderPin2);

  int encoded = (MSB << 1) |LSB;
  int sum = (lastEncoded << 2) | encoded;

  if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++;
  if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --;

  lastEncoded = encoded;
  }

thank you for your suggestion. The issue isn't with the code but was with the button. I changed the button and it worked fine. Thanks for the help!


Adafruit DHT22 Library + Arduino Due not compiling? i recently purchased a DHT22's and tried to get it to work using Adafruit's DHT library on Github.
When i compile it with a Arduino DUE, it gives me the following error:

C:\Users\Moz\Documents\Arduino\libraries\DHT-sensor-library-master\DHT.cpp: In constructor 'DHT::DHT(uint8_t, uint8_t, uint8_t)':
C:\Users\Moz\Documents\Arduino\libraries\DHT-sensor-library-master\DHT.cpp:14:9: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]
   _port = digitalPinToPort(pin);
         ^
Error compiling.

It compiles on a Arduino Uno but not on the DUE.

What is the reason for this?

Edit: Below is the example code i use

#include "DHT.h"

#define DHTPIN 2     // what pin we're connected to

#define DHTTYPE DHT22   // DHT 22  (AM2302)

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");
  dht.begin();
}

void loop() {

  delay(2000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);

  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F");
}

There are several Arduino libraries for reading DHT22 and related DHT sensors.  The Adafruit DHT library does not compile for the Due since it uses AVR specific functions not available on ARM (Due).

For the Arduino Due use Rob Tillaart's DHTstable library available from his github page where you can download a zip file.  Note that his project also has a "DHTlib" library which does not support the Due.  There exists yet more DHT libraries which Rob has listed on the DHTLib page on arduino.cc.


Capacitors in DC circuits I have a question about capacitors in DC (digital) circuits. The picture below is an edited schematic of the Arduino Uno R3.

The DTR line is connected to the reset input of the Atmega328 by a 0.1uF capacitor.

The capacitor is needed to initiate a load to the atmega flash memory through the USB -> UART. Why is this the case, everything I have been taught says "Capacitors block DC and let AC through"

All I see is something that can let AC noise through to the Arduino reset? I know its needed, I tested it. But why its needed, how it fulfils that function I have no idea.

Please help

The Atmel datasheet, page 305, Section 29.5 "System and Reset Characteristics" provides some useful information for the reset pulse. It says that the worst-case minimum pulse width is \$2.5\:\mu\textrm{s}\$. It then goes on to say that the ramp rate has to be contained between two boundaries; no faster than \$10\:\frac{\textrm{kV}}{\textrm{s}}\$, but also no slower than \$10\:\frac{\textrm{V}}{\textrm{s}}\$. So there are some restrictions that should be managed by any reset system.

There are some nice reset circuit ICs available which provide a manual reset input as well as a control line. I'd probably use one of those about a circuit I cared about. Okay. Actually, I'd make my own out of a PIC10LF320 in a SOT-23-6, which also includes a brown-out circuit of its own, which I'd probably also re-purpose, as well.

But let's look at this circuit. DTR is normally held HIGH (I believe) and is pulled LOW in order to initiate a reset. Assuming that the two MCUs are running on different power rails (or the same, doesn't matter), \$C_5\$ is charged up to the difference between the ATmega328's rail (via \$RN_1\$ and the DTR output line's HIGH value.) If there is no difference, the voltage will be nearly zero. But if the rails are different, then there will be a small voltage across \$C_5\$ that represents this difference.

When DTR is pulled LOW, that end of \$C_5\$ is also pulled down to that voltage (close to ground.) For the first moments, this also means that the other side of \$C_5\$ is similarly pulled downwards, too. If there was some voltage rail difference, then that's the voltage that appears at the reset pin of the ATmega328. Depending on the voltage differences between the MCUs and the reset pin requirements of the ATmega328, this could be a problem. The datasheet says that it may be required to be as low as \$600\:\textrm{mV}\$, though the typical only requires to be pulled down to \$1.3\:\textrm{V}\$. But if no difference in the rails, then hopefully near-ground appears at the reset pin of the ATmega328. I'm going to assume there is no difference, here, so that we at least have a good chance it works okay.

Now, as soon as \$C_5\$ is yanked down by DTR, \$C_5\$ begins charging up through \$RN_1\$, starting at a rate of about \$500\:\mu\textrm{A}\$. The time constant is \$1\:\textrm{ms}\$. So the voltage will rise rapidly. Assume that we only just barely achieved the required \$600\:\textrm{mV}\$ at the start (the capacitor held a slight charge.) Then we'd cross over the minimum rising threshold of \$1.1\:\textrm{V}\$ within about \$100\:\mu\textrm{s}\$. This is well more than long enough for the earlier mentioned minimum reset pulse width of \$2.5\:\mu\textrm{s}\$. So the spec is met here.

Now, let's go the other direction. Let's say that now DTR is held LOW for a long enough time that it charges up to about \$5\:\textrm{V}\$ through \$RN_1\$. Now, DTR is driven HIGH. What happens? Well, the other side of \$C_5\$ will now be at about \$10\:\textrm{V}\$ (the \$5\:\textrm{V}\$ charge on \$C_5\$ added to the DTR HIGH voltage value.) This is rapidly discharged, safely, via \$D_2\$. That's why \$D_2\$ was added. Otherwise, this voltage would be presented to the RESET pin of the ATmega328 and would have to be discharged via any internal protection diodes present there (which may themselves have additional specifications that must be met.)

What's interesting here is that the RESET pin in particular is called out in the datasheet on page 299. It says that it can support up to \$13\:\textrm{V}\$ worst case. So, technically, that might mean that \$D_2\$ isn't necessary to avoid driving protection diodes in the CPU. But it is still a good idea for an entirely different reason. This is to discharge \$C_5\$ rapidly (it would be very slow, via \$RN_1\$), so that it can be used for another reset very soon after being used.

Note on the reset pin:

As Majenko added in a comment, there is a high voltage programming mode for Atmel devices like this. I frankly don't fully apprehend it, as I haven't read a datasheet on the topic. But I did find out from an Atmel video that the PC6/RESET line, which normally acts like a /RESET line, can be changed into operating like a general purpose I/O port by changing the RSTDISBL fuse, which makes the general I/O function available. The bad thing about that is that the ISP programming mode NEEDS the /RESET line to do its job. So you can't program the device anymore, if you set up that fuse. This then forces you to use the parallel programming mode that is entered using the high voltage programming mode. I would guess that entering this mode uses the /RESET pin again, but this time places a high voltage on it that is detected in order to put the device into its parallel programming mode instead of the ISP programming mode.

I can't readily find a specific programming document on the details of using this mode to program their devices. Microchip publishes them. But it appears, cursory examination only, that Atmel does not. They document how to use the mode with their tools, such as the STK500 (which I have.) But not how to design your own tool. I'm guessing, for now, that this is a matter of non-disclosure for Atmel. And given that they have it available for so many different devices, I can see why they might want to avoid having to support it.

The details on this pin are starting to get complicated-sounding. But pins cost money and silicon is cheap. So Atmel, like other companies, try to come up with methods to use their scarce pins to provide as much versatility as they can to sell devices.

That's it.