Software PWM implementation on ATTiny44 screws up timing functions I've came up with a poor man's implementation of software-based PWM for the ATTINY44 and I'm kinda stuck now. It works but it screws up the timing functions badly (delay, delayMicroseconds) no matter what timer I use for the ISR (timer 1 or 0). The delay in my example is more like 1 second than 100ms. Can somebody point out what I'm doing wrong? :)

uint8_t pwmled[11] = {0};
volatile uint8_t currentStep = 0;
uint8_t p[11] = {PORTA0, PORTA1, PORTA2, PORTA3, PORTA4, PORTA5, PORTA6, PORTA7, PORTB0, PORTB1, PORTB2};

void initTimer1() {
  cli();
  TCCR1B = (1 << WGM12) | (1 << CS10);
  OCR1A = 64;
  TIMSK1 = (1 << OCIE1A);
  sei();
}

ISR(TIM1_COMPA_vect) {
  if (currentStep < 100)
    currentStep += 1;
  else
    currentStep = 0;
  for (uint8_t x = 0; x <= 10; x++)
    (currentStep < pwmled[x]) ? (x < 8 ? PORTA |= (1 << p[x]) : PORTB |= (1 << p[x])) : (x < 8 ? PORTA &= ~(1 << p[x]) : PORTB &= ~(1 << p[x]));
}

void setup() {
  initTimer1();
  for (int i = 0; i <= 10; i++) {
    pinMode(i, OUTPUT);
    pwmled[i] = 1;
  }
}

void loop() {
  pwmled[random() % 11] = random() % 100;
  delay(100);
}

What you are doing wrong is:

The problem is your interrupt handling routine lasts too long. Since inside ISR() interrupt flag is automatically cleared, timer0 interrupts are being missed and delay() depends upon timer0 interrupts.

To confirm the problem is ISR, remove the for loop and just toggle one pin instead. I bet the delay will then be as it should.

Try to put sei() at the beginning of your ISR to see what is going to happen with the timming of the delay - but that is not the right way.

Instead of using delay() (based on timer0) you can count the number of timer1 interrupts but ISR routine must not last longer than the time between two interrupts and your ISR spends quite a few T-states inside the for loop. A rule of a thumb is ISR has to be very short (fast) - unless you really know what you are doing. For example, in one of my devices I am using a very long ISR routine (in fact the firmware consists of only the ISR - there is only sleep_mode(); in main) for which I know it sometimes lasts longer than the time window between interrupts and I know some of the interrupts are occasionally being missed. However, these few missed interrupts are not critical to that particular application and I am sure the interrupts are being missed rarely.

You could change OCR1A value to increase the time between interrupts but then you would have lower PWM frequency.


Sampling Rate of Arduino Uno It might be a stupid question but, I am currently using Arduino Uno with the 16MHz processor, what is maximum sampling rate of data available to me if I want to read data of a sensors such as accelerometer?

I have a page about I2C. The speed of I2C depends on a number of things, such as the I2C clock (which you can change) and also how many data bytes are in a "packet". There is a fixed overhead of the device address in each packet.

A broad rule-of-thumb would be around 4700 bytes per second for a single-byte payload at the default clock rate. You may also need to spend time asking for a reading. I haven't read the datasheet (which you didn't link).

The datasheet for the MPU6050 may give you more information about how fast it can respond.


Sending MIDI CC to multiple midi Channel Hi so i would like to send CC messages to different MIDI Channel (volume control). The CC messages are coming from one knob.

The solution i found kind of work but i'm pretty sure is not ideal and seems to introduce drift or lag: the volume isn't getting the same value from one channel to another.

My question is: is there a better way to do it than what i have done.

I use and tweak the following exemple provided in the Teensy Exemple library "USB MIDI AnalogControlChange Example"

The exemple was using this line of code to send CC (controlChange) to a specific channel:

MIDI.sendControlChange(controlNumber, controlValue, channel);

As i wanted to have multiple target channels for the third parameter i tried things like this:

MIDI.sendControlChange(controlNumber, controlValue, 1-2-3);

or

MIDI.sendControlChange(controlNumber, controlValue, (1,2,3));

or

MIDI.sendControlChange(controlNumber, controlValue, 1+2+3);

But it didn't worked. I didn't find in the documentation if this parameter could accept more than one number.

What worked is to multiply analog read of the same knob and multiply the sent message. It's not elegant (i'm new to programing of course) but also i noticed i strange latency or drift if you will: the volume of the channel did went from 0 to full volume but the one on channel 2 didn't go to zero, so the purpose failed. The idea here is to have all the midi channels (1 to 8) but the 11 to be affected by the volume knob.

Hope you can help, in advance, thanks

    /* USB MIDI AnalogControlChange Example

   You must select MIDI from the "Tools > USB Type" menu
   http://www.pjrc.com/teensy/td_midi.html

   This example code is in the public domain.
*/

#include <Bounce.h>

// the MIDI channel number to send messages
const int channel = 11;

// the MIDI continuous controller for each analog input
const int controllerA9 = 1; // param 1
const int controllerA8 = 2; // param 2
const int controllerA7 = 3; // cutoff
const int controllerA6 = 4; // reso
const int controllerA5 = 16; // volume (for channel 11)
const int controllerA4 = 16; // volume (for other channels exept 11

void setup() {

}

// store previously sent values, to detect changes
int previousA9 = -1;
int previousA8 = -1;
int previousA7 = -1;
int previousA6 = -1;
int previousA5 = -1;
int previousA4 = -1;

elapsedMillis msec = 0;

void loop() {
  // only check the analog inputs 50 times per second,
  // to prevent a flood of MIDI messages
  if (msec >= 20) {
    msec = 0;
    int n0 = analogRead(A9) / 8;
    int n1 = analogRead(A8) / 8;
    int n2 = analogRead(A7) / 8;
    int n3 = analogRead(A6) / 8;
    int n4 = analogRead(A5) / 8;
    int n5 = analogRead(A4) / 8;
    int n6 = analogRead(A4) / 8; //i duplicated this to be able to have a different channel target
    // only transmit MIDI messages if analog input changed
    if (n0 != previousA9) {
      usbMIDI.sendControlChange(controllerA9, n0, channel);
      previousA9 = n0;
    }
    if (n1 != previousA8) {
      usbMIDI.sendControlChange(controllerA8, n1, channel);
      previousA8 = n1;
    }
    if (n2 != previousA7) {
      usbMIDI.sendControlChange(controllerA7, n2, channel);
      previousA7 = n2;
    }
    if (n3 != previousA6) {
      usbMIDI.sendControlChange(controllerA6, n3, channel);
      previousA6 = n3;
    }
    if (n4 != previousA5) {
      usbMIDI.sendControlChange(controllerA5, n4, channel);
      previousA5 = n4;
    }

    if (n5 != previousA4) {
      usbMIDI.sendControlChange(controllerA4, n5, 1);
      previousA4 = n5;
    } // 1 here is the channel who's different from the int channel = 11

     if (n6 != previousA4) {
      usbMIDI.sendControlChange(controllerA4, n6, 2);
      previousA4 = n6;
    } // 2 here is the channel who's different from the int channel = 11

  }

  // MIDI Controllers should discard incoming MIDI messages.
  // http://forum.pjrc.com/threads/24179-Teensy-3-Ableton-Analog-CC-causes-midi-crash
  while (usbMIDI.read()) {
    // ignore incoming messages
  }
}

A single CC message applies to a single channel. If you want to affect multiple channels, you have to send multiple messages:

usbMIDI.sendControlChange(controllerAx, nx, 0);
usbMIDI.sendControlChange(controllerAx, nx, 1);
usbMIDI.sendControlChange(controllerAx, nx, 2);
usbMIDI.sendControlChange(controllerAx, nx, 3);
...

And this should of course be done in a loop:

for (int c = 0; c < 16; c++)
    if (c != 10)
        usbMIDI.sendControlChange(controllerAx, nx, c);


Time between two IR beam sensors I am working with two sets of IR beam, they are to be placed in X distance. My goal is to measure speed. I would like to measure time between the first IR beam to the second beam when the beam breaks.

I am not sure what's going on, I am not getting any time of the serial port but the LEDs are turning on and off the way I wanted.

Please help me with getting the time between two IR beam sensors.

This the sensor that I am using -  Adafruit IR breakbeam sensors
and I am working with a Mega2560.

#define LEDPIN 13
int startPin = 8, finishPin = 5;
unsigned long starttime = 0, finishtime, time_interval;
float distance = 1, Speed; // Speed calculated
int trigger1 = 0; // Sensor 1
int trigger2 = 0; // Sensor 2
int sensor1State; // Sensor 1 status
int sensor2State; // Sensor 2 status

void setup() {
  pinMode(startPin, INPUT_PULLUP); // Sensor 1 as input
  digitalWrite(startPin, HIGH); // Turn on the pullup
  pinMode(finishPin, INPUT_PULLUP); // Sensor 2s input
  //digitalWrite(finishPin, HIGH); // Turn on the pullup

  pinMode(LEDPIN, OUTPUT);
  time_interval = ((finishtime - starttime) / 1000000);
  Serial.println(time_interval);
}

void loop() {
  sensor1State = digitalRead(startPin); // Read the state of the IR sensor 1:
  if (sensor1State == LOW) // See if IR beam of sensor 1 has been broken
  {
    if (trigger1 == 0 && trigger2 == 0) // Check to make sure both sensors have not triggered
    {
      starttime = micros(); // Save time when sensor 1 was triggered
      digitalWrite(LEDPIN, HIGH);
      trigger1 = 1; // Prevent sensor 1 from triggering again
    }
  }
  if (trigger1 == 1) {
    sensor2State = digitalRead(finishPin); // See if IR beam of sensor 2 has been broken
    if (sensor2State == LOW) {
      // Check to make sure sensor 1 has triggered but not sensor2
      if (trigger2 == 0) {
        // Run speed function
        trigger2 = 1;
        finishtime = micros(); // Save time when sensor 2 was triggered
        digitalWrite(LEDPIN, LOW);
        // time takes to travel between 2 IR Beam  // divide by 1000000 to convert microsecond to second
        Serial.println(time_interval);
      }
      // Reset both sensors
      trigger1 = 0;
      trigger2 = 0;
    }
  }
}

You've tried to print an interval at the bottom of the setup() function, using finishtime before you have ever used it. Fortunately, finishtime will have been initialized to zero before the program runs so the the arithmetic result will be zero, though meaningless.

In loop(), you've never completed the interval calculation before you try to print it.

If nothing at all is being printed, check your wiring and be sure your code is getting the triggers. You haven't showed your wiring, so we can't help you debug that, in case there is a problem with that also.


Arduino Uno's Timer maximum frequency using Timer Compare Interrupt, not Timer Output Pins (e.g. OC0A) I want to achieve the generation of a custom binary signal over a digital pin at the highest possible frequency on Arduino Uno.
Using Timer's output pins (e.g. OC0A), one can get a pin to toggle at a maximum frequency of 16MHz (which corresponds to a sqaure wave of frequency 8MHz), as described here:
Maximum frequency of digital signal in Arduino Uno?
However as far as I understand, Timer's output pins are only useful if one needs to generate a repetitive waveform such as a PWM or square wave, so it cannot serve my purpose which requires the generation of a custom binary signal.
Using the following code, I was expecting digital pin 9 to toggle at a frequency close to 16MHz too, since I use no prescaler and set the Compare Match Register value to 0:
void setup()
{
    DDRB = 1 << 1;  // Set D9 as OUTPUT

    cli();
    TCNT0 = 0; TCCR0A = 0; TCCR0B = 0;
    TCCR0A |= (1 << WGM01);  // CTC mode
    TCCR0B |= (1 << CS00);  // no prescaling
    OCR0A = 0;  // Highest timer overflow frequency possible
    TIMSK0 |= (1 << OCIE0A);
    sei();
}

ISR(TIMER0_COMPA_vect)
{
    PORTB ^= 1 << 1;  // Toggle D9; this allows to measure the toggle frequency, however this could be replaced by some code to generate a custom binary signal
}

void loop(){}

However in fact it appears to toggle at a frequency of only approximately 410kHz (which corresponds to a square wave of frequency 205kHz), as the below image shows:

I used Timer0 but I get the same frequency with Timer1 and Timer2.

How can one explain that using this code I get this toggle frequency on the digital pin ?
How can I generate a custom binary signal over a digital pin at the highest possible frequency ?

How can one explain that using this code I get this toggle frequency on the digital pin ?

Code takes time to execute. Your ISR, when compiled, looks like:
ISR(TIMER0_COMPA_vect)
{
 124:   1f 92           push    r1
 126:   0f 92           push    r0
 128:   0f b6           in  r0, 0x3f    ; 63
 12a:   0f 92           push    r0
 12c:   11 24           eor r1, r1
 12e:   8f 93           push    r24
 130:   9f 93           push    r25
    PORTB ^= 1 << 1;  // Toggle D9; this allows to measure the toggle frequency, however this could be replaced by some code to generate a custom binary signal
 132:   85 b1           in  r24, 0x05   ; 5
 134:   92 e0           ldi r25, 0x02   ; 2
 136:   89 27           eor r24, r25
 138:   85 b9           out 0x05, r24   ; 5
}
 13a:   9f 91           pop r25
 13c:   8f 91           pop r24
 13e:   0f 90           pop r0
 140:   0f be           out 0x3f, r0    ; 63
 142:   0f 90           pop r0
 144:   1f 90           pop r1
 146:   18 95           reti

That's 18 assembly instructions, each needing between 1 and 4 clock cycles to execute.  Referencing the datasheet you can count the exact cycles needed and sum them up, yielding 31 clock cycles.
Toggling at maximum speed that would be 16MHz / 31 = 516kHz.
And then you have the rest of the code running between each call to the interrupt, so it's slower than that.

How can I generate a custom binary signal over a digital pin at the highest possible frequency ?

By not using interrupts, and writing a tight loop in assembly language.


BLE Mate 2 bluetooth module to Arduino Uno without FTDI SmartBasic So I'm trying to hook up this BLE breakout board to an Arduino Uno. SparkFun has a hookup guide which seems to be great for someone who has an FTDI SmartBasic that is mentioned in the article. I don't have the SmartBasic board, and would like to see if this is possible without it.

I have hooked up the board to my Uno with the following pinouts:

GRN -> Reset
RXI -> RX (tried with TX as well)
TXI -> TX (tried with RX as well)
VIN -> Tried 5V and 3.3V
CTS -> GND
BLK -> (No Connection)

I use their example code they have provided, uploaded without the RX and TX pins hooked up because, from what I notice, you cannot upload a program through the USB serial when these ports are in use. So after I upload the program through USB, I power the board with a battery and connect the RX and TX pins to the BLE board.

Has anyone either successfully hooked these up without the use of a SmartBasic? I'm a programmer by trade so I do my best to understand this side of the spectrum.

So I found out what I was doing wrong, and want to smack myself for it -.-

The answer was to simply hook up the BLK connection (which I guess is also ground) to a GND pin on the Arduino Uno.

Hope this ends up helping someone out.


Receiving SMS by Arduino GSM Shield and control the LED with the content of this SMS? I am using Arduino GSM Shield receiving SMS from an Android app. And the content of this SMS will control a LED. If the content of this SMS is not "off", the LED will be on and the content will be printed in the serial monitor. But if it is "off", the LED will be off immediately. Besides, the LED will keep being on until the "off" message coming. For now, I used the code from the example of the software. But I cannot use the content of this SMS to control the status of LED. With the code below, the LED could not be turned on and the content could not be displayed on the monitor. I think it was because the sketch failed to get the whole content of this SMS. Could anybody tell me how to solve this problem? Thanks.

#include <GSM.h>
GSM gsmAccess;
GSM_SMS sms;
char senderNumber[20];
int led=13;
void setup()
{
  Serial.begin(9600);
  pinMode(led,OUTPUT);
  digitalWrite(led,LOW);
  while (!Serial) {
    ;
  }
  Serial.println("SMS Messages Receiver");
  boolean notConnected = true;
  while(notConnected)
    {
      if(gsmAccess.begin("6442")==GSM_READY)
        notConnected = false;
      else
        {
          Serial.println("Not connected");
          delay(1000);
        }
    }
  Serial.println("GSM initialized");
  Serial.println("Waiting for messages");
}

void loop()
{
  char c;
  int val=0;
  val=digitalRead(led);
  if (val==HIGH){
    digitalWrite(led,HIGH);
  }
  if (sms.available()){
    Serial.println("Message received from:");
    sms.remoteNumber(senderNumber, 20);
    Serial.println(senderNumber);

    if(sms.peek()=='#')
      {
        Serial.println("Discarded SMS");
        sms.flush();
      }
    while(c=sms.read())
      if(c='off'){
        digitalWrite(led,LOW);
      }else{
        digitalWrite(led,HIGH);
        Serial.print(c);
      }
    Serial.println("\nEND OF MESSAGE");
    sms.flush();
    Serial.println("MESSAGE DELETED");
  }
  delay(1000);
}

First of all, you have a typo: You need the double-equals operator in

if (c == 'off') {

But more importantly, you can't use a char variable to hold or compare more than one character at a time. I don't know the details of the Arduino GSM library, but if sms.read() returns a string, then you'll need a string variable or an array of char to hold the result.


Arduino GSM shield GSM_READY not ready ever I am using an Arduino Mega and an Arduino GSM shield. I am using the receive SMS example under GSM in the Arduino IDE. My GSM shield's hardware IP is set correctly.

Here is the sketch:

/*
 SMS receiver

 This sketch, for the Arduino GSM shield, waits for a SMS message
 and displays it through the Serial port.

 Circuit:
 * GSM shield attached to and Arduino
 * SIM card that can receive SMS messages

 created 25 Feb 2012
 by Javier Zorzano / TD

 This example is in the public domain.

 http://arduino.cc/en/Tutorial/GSMExamplesReceiveSMS

*/

// include the GSM library
#include <GSM.h>

// PIN Number for the SIM
#define PINNUMBER ""

// initialize the library instances
GSM gsmAccess;
GSM_SMS sms;

// Array to hold the number a SMS is retreived from
char senderNumber[20];

void setup() {
  // initialize serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("SMS Messages Receiver");

  // connection state
  boolean notConnected = true;

  // Start GSM connection
  while (notConnected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY)
      notConnected = false;
    else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("GSM initialized");
  Serial.println("Waiting for messages");
}

void loop() {
  char c;

  // If there are any SMSs available()
  if (sms.available()) {
    Serial.println("Message received from:");
    // Get remote number
    sms.remoteNumber(senderNumber, 20);
    Serial.println(senderNumber);
    // An example of message disposal
    // Any messages starting with # should be discarded
    if (sms.peek() == '#') {
      Serial.println("Discarded SMS");
      sms.flush();
    }

    // Read message bytes and print them
    while (c = sms.read())
      Serial.print(c);
    Serial.println("\nEND OF MESSAGE");

    // Delete message from modem memory
    sms.flush();
    Serial.println("MESSAGE DELETED");
  }
  delay(1000);
}

The issue is this line:

if (gsmAccess.begin(PINNUMBER) == GSM_READY)

The serial monitor outputs everything until that line.

It just never gets past it, so I assume it cannot connect? The SIM has no pin code: I have tried it with my phone. The SIM has full signal strength when in my phone. I have tried my other SIM card also but the same thing happens.

This seem to be the same question, yet no answer:
http://forum.arduino.cc/index.php?topic=270551.0

You could always try setting a pin code and then retry
http://arduino.cc/en/Tutorial/GSMToolsPinManagement

What version of the Arduino IDE are you using ? Also, are you sure you are suppying the board correctly ? "It is recommended that the board be powered with an external power supply that can provide between 700mA and 1000mA. Powering an Arduino and the GSM shield from a USB connection is not recommended, as USB cannot provide the required current for when the modem is in heavy use."


Differences between nodemcu and arduino processer I have an arduino Uno and nodemcu development board.

I have an OV7076 camera and used with arduino UNO. It worked flawlessly with it and the code used is provided in the [Instructables tutorial][2] named as FromComputerNerd.ino.

Now i want to use it with Nodemcu. Whereas Nodemcu have a single Analog input but OV7076 uses two analog inputs [shown in][2]. So to get it I am trying to use Multiplexer. I can change the code so that it would adjust for analog pins.

But will the code be compatible with Nodemcu. Since it was written for arduino uno.If not, What changes can be done to make it compatible?

http://www.instructables.com/id/OV7670-Without-FIFO-Very-Simple-Framecapture-With-/

Camera doesn't send data via Analog to Arduino.
A5 and A4 are I2C bus beside Analog.

NodeMCU has Software I2C protocol bus too, You can use D1 (GPIO 5) as CLK, and D2 (GPIO 4) as SDA.

see : https://github.com/esp8266/Arduino/blob/master/doc/libraries.rst#i2c-wire-library


Highly sensitive light sensor to calculate number of times each color LED blinks I am working on a project and got stuck on a point, and I hope somebody will guide me. I have a hardware device which has different color LEDs (green, red and yellow) and I have to calculate how many times each color LED glows for each mode of operation.

The LEDs that are connected to the device are pretty small and will blink only for a couple of seconds, ao I am looking for a very sensitive light sensor.

So what kind of light sensor do I have to use with Arduino UNO to achieve this?

Should I go for BH1750 or do you have any other suggestion?

Thanks in advance.

Like the OP wrote, you can use very simple sensors, like a phototransistor.
Even simpler, if you can somehow isolate each pair LED-phototransistor, you don't even need to care about the color of the led, just use some bluetac to stick one phototransistor on top of each LED and only measure the brightness.

edit:

A quick check on ebay shows the 3DU5C as good candidate: it has a metallic container, so it is more directional than one with full plastic body.

3DU5C ebay link  and  datasheet

It is shown to have a peak response at 880nm (red light), so you might not be able to use it directly as digital input for the other 2 colors you want to monitor and instead have to treat it as analog reading.

OTOH if you use them all as analog inputs, you will not have to add the resistor that would be required for binary mode.


Receiving two-byte int values over serial I am using Python smbus write_word_data method to send int values from a Raspberry Pi to an Arduino using I²C.

This seems to be the correct method.

When I send values from 0-255, I see the following in my Arduino serial monitor

  0,0,0
  0,1,0
  0,2,0
  …
  0,255,0

Sending 256 I see:

  0,0,1

For 257 I see:

  0,1,1

Etc, etc...

My question is, how would I modify the following Arduino code to properly 'reconstitute' the int values, and then send them back to the RPi?

#include <Wire.h>

#define SLAVE_ADDRESS 0x04
int number = 0;
int state = 0;
bool newData = false;

void setup() {
  pinMode(13, OUTPUT);
  Serial.begin(9600);
  // initialize i2c as slave
  Wire.begin(SLAVE_ADDRESS);
  // define callbacks for i2c communication
  Wire.onReceive(receiveData);
  Wire.onRequest(sendData);
  Serial.println("Ready!");
}

void loop() {
  Serial.println(receivedValue);
  newData=false;
}

// callback for received data
void receiveData(int byteCount) {
  while(Wire.available()) {
    newData = true;
    Wire.read();
    if(Wire.available() == 2) {
      receivedValue = Wire.read() | Wire.read() << 8;
    }
  }
}

// callback for sending data
void sendData() {
  Wire.write(number);
}

void receiveData(int byteCount){

  // Looks like your number is sent in a 3 byte packet
  if (bytecount == 3)
  {

    // Discard first number as it is seemingly alway zero
    Wire.read();

    // Read low byte into rxnum
    int rxnum = Wire.read();

    // Read high byte into rxnum
    rxnum += Wire.read() << 8;

    // Send back
    sendInt(rxnum);

  }

}

void sendInt(int num){

  // Uncomment below if you want so send back in same format
  // Wire.write(0);

  // Send low byte
  Wire.write((uint8_t)num);

  // Send high byte
  num >>= 8;
  Wire.write((uint8_t)num);
}


Question about infrared receiver with metal shell to detect heart pulse rate? I'm newbie to the world of arduino and environmental sensing. I have been searching for a while about how can I measure the heart pulse rate, I came through the following tutorial:

Click Here

I have the following Arduino IR Receiver with metal shell module that I want to use as the previous tutorial suggesting, but, the IR receiver used in the tutorial has no metal shell, so, my question is if they are both functioning the same way?
Can I position my IR Receiver exactly as the one in the tutorial or do I need some workaround to reach my goal based on the fact that it has a metal shell?
Thanks in advance.

"Proper" oxygen meters use a bimodal LED - red + IR - so there will be limitations to this. They also have a piece of copper foil wrapped around the sensor & heavily earthed, so your shielded sensor has, already, an advantage!

You should be able to use your receiver exactly the same way. If you can ground the shield, do so.


Is setting clock divider worth changing on delay() to save power? Along all the "advanced" methods described in this article, does simple method as downscaling processor while delay makes a difference on power consumption? How much time does the clock alternation takes itself?

Is below example valid?

#include <avr/power.h>

void setup() {}

void loop {

    /*
       here some jobs to do...
    */

    clock_prescale_set(clock_div_256); // downscale clock
    delay(200); // wait
    clock_prescale_set(clock_div_1); // restore clock
}

Reducing the CPU frequency should work, but I would expect better
savings by sleeping during the busy loop:

#include <avr/sleep.h>

void sleepy_delay(uint32_t duration)
{
    uint32_t start = millis();
    while (millis() - start < duration) {
        sleep_mode();
    }
}

Note that the sleep will be interrupted at least on every Timer 0
overflow interrupt, which happens every 1024 µs (that's what
increments the value returned by millis()), so there is no risk of
oversleeping. You could add some power_*_disable() calls for better
savings.


ESP8266 not accessing PHP file I'm trying to control NodeMCU via Android application and I can control NodeMCU easily but when I added the URL to hit the PHP code to enter data in MYSQL, neither NodeMCU is controllable nor NodeMCU is hitting the PHP code. I'm confused with content type: text/html - I'm not sure where to set this piece. Is there any mistake I'm doing or anything I'm missing?

Following is the ESP8266 code on Arduino IDE:

#include <ESP8266WiFi.h>

const char* ssid = "ssid";
const char* password = "password";
const char* host = "aoatech.ml";

WiFiServer server(3000);
int light1 = 13;
int light2 = 15;
int fan = 12;
int socket = 14;
String what;
int which;
String mac;

void setup() {
  Serial.begin(115200);
  delay(10);
  pinMode(light1, OUTPUT);
  pinMode(light2, OUTPUT);
  pinMode(fan, OUTPUT);
  pinMode(socket, OUTPUT);
  digitalWrite(light1, 0);
  digitalWrite(light2, 0);
  digitalWrite(fan, 0);
  digitalWrite(socket, 0);
  Serial.print("Connecting to: ");
  Serial.print(ssid);
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  server.begin();
  Serial.println("Server started");
  Serial.println(WiFi.localIP());
}

void loop() {
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  Serial.print("Connecting to ");
  Serial.println(host);
  //  const int httpPort = 3000;
  //  if (!client.connect(host, httpPort)) {
  //    Serial.println("Connection failed!");
  //    return;
  //  }
  mac = WiFi.macAddress();
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();
  int val;
  if (req.indexOf("/light1/1") != -1){
    val = 1;
    what = "Light_1";
    which = light1;
  }
  else if (req.indexOf("/light1/0") != -1){
    val = 0;
    what = "Light_1";
    which = light1;
  }
  else if (req.indexOf("/light2/1") != -1){
    val = 1;
    what = "Light_2";
    which = light2;
  }
  else if (req.indexOf("/light2/0") != -1){
    val = 0;
    what = "Light_2";
    which = light2;
  }
  else if (req.indexOf("/fan/1") != -1){
    val = 1;
    what = "Fan";
    which = fan;
  }
  else if (req.indexOf("/fan/0") != -1){
    val = 0;
    what = "Fan";
    which = fan;
  }
  else if (req.indexOf("/socket/1") != -1){
    val = 1;
    what = "Socket";
    which = socket;
  }
  else if (req.indexOf("/socket/0") != -1){
    val = 0;
    what = "Socket";
    which = socket;
  }
  else {
    Serial.println("invalid request");
    client.stop();
    return;
  }

  digitalWrite(which, val);

  String url = "http://aoatech.ml/hitthis.php?room=Bed%20Room%201";
  url += "&state=";
  url += val;
  url += "&button=";
  url += what;
  url += "&mac=";
  url += mac;

  Serial.print("Requesting URL: ");
  Serial.println(url);

  client.flush();
  //  client.println("HTTP/1.1 200 OK");
  //  client.println("Content-Type: text/html");
      client.print(String("GET ") + url + " HTTP/1.1\r\n" +
           "Host: " + host + "\r\n" +
           "Connection: close\r\n\r\n");
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }
  client.println("");
  client.print(what + " is now: ");

  if(val == 0) {
    client.print("Off");
  } else {
    client.print("On");
  }
  Serial.println("Client disonnected");
}

Your PHP server has a certain content type it can receive to process your requests from the ESP8266. The two most generic content-types used for php are either application/x-www-form-urlencoded or multipart/form-data. Try to play with those two and see if that solves it for you.


Serial communication using Arduino and TeraTerm I wrote a simple serial program using Arduino Mega 2560, it is connected to COMPORT 10. Here is the program I Wrote,

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

void loop()
{
  Serial.println("HELLO");
  delay(1000); //Send every one second
}

Now, I tried to send this message "Hello" to TeraTerm (COMPORT 1, for this I just hooked up Tx and Rx to the Arduino's Rx0 and Tx0. Doing this I do receive message in my TeraTerm screen but the received message doesn't make sense, its receiving garbage. Its not the case of mismatch of baud rate I am using 9600 on both the side.

However I do receive message "HELLO" in the serial monitor. Is there something I am doing wrong that I am not receiving message on TeraTerm.

... I just hooked up Tx and Rx to the Arduino's Rx0 and Tx0.

But neither device knows what voltage they are. You need to connect ground as well so that they have a common reference.


How can I make Arduino IDE use Atmel's provided toolchain? (Linux/Ubuntu) I have an Arduino based board using ATmega168PB, but so far only Atmel's provided toolchain supports this microcontroller. I can download the toolchain from Atmel's website, but I am not sure how to make the Arduino environment use it.

In the directory for the new core create a new platform.txt and give the entry for compiler.path the location of the bin/ directory containing the Atmel toolchain.

compiler.path=/path/to/bin/


Arduino not detected I took an Arduino from a friend yesterday but when I connect it to the laptop there is no light blinking from the Arduino and the laptop doesn't detect any device.

Is there a problem with the Arduino or is there a possibility that the USB has problems?

Are you sure your laptop doesn't detect any device? It is possible that you need to install right driver for your arduino. The problem could be with:

Cable: Try to replace it with a working cable
Drivers Issue: You need to install driver for your Arduino. Generally, your laptop will issue warnings if it didn't find any appropriate driver for it.
USB-To-UART Bridge: This is an IC in arduino board. It needs to be working for laptop to detect your board.
Microcontroller: Since, you told us that your board is blinking, then microcontroller will be working for sure.

Can you see any part getting hotter? Have you tried with other laptop and cable?


Make a float using integers I want to make a floating point number that has only one decimal point.
I have separate integers for both side.
Ex:

int n1 = 8;

int n2 = 2;

I want to make 8.2 as float value using separate integers.
Please give me a solution.

Seems too simple:

float x = n1 + n2 * 0.1;

Is there a trick?

Edit: The method proposed by Michel Keijzers, namely

float x = n1 + n2 / 10.0;

(I removed the redundant casts) can be slightly more accurate, but takes
longer to compute, because division is significantly slower than
multiplication on the Uno. Computing n2/10.0 always yields the
correctly rounded result, namely the float that best approximates the
exact mathematical result. On the other hand, n2*0.1 involves two
rounding operations: one at compile time, in the representation of 0.1
(which is not an exact float), another at run time, which rounds the
result of the multiplication. If n2 is between 0 and 8, you end up
getting the correctly rounded result anyway, just as with n2/10.0.
However, if n2 is 9, then

n2*0.1 yields 0.900000035762786865234375 (error ≈ 3.6e-8)
n2/10.0 yields 0.89999997615814208984375 (error ≈ -2.4e-8)

The former carries a rounding error 1.5 larger than the latter.


SeeedDuino/Grove and the story of not being able to upload programs I am new to the arduino world and wanted to start playing with the micro controllers, I am a .NET developer by trade so not completely new to this kind of world.

I purchased a seeedduino v3 and a Grove started kit (No soldering skills here) and can't even get the basics to work.

I am setting up a simple button to light up the LED program. I have had it run once or twice but it seems really hit or miss on whether or not the Arduino IDE actually gets the program onto the seeedduino.

Arduino IDE (1.5.6-r2) set-up:
Followed setup instructions found here: SeeedDuino v3

Board: Arduino Duemilanove or Diecimila
Processor: ATmega328
Port: COM4 [this is what popped up once device was plugged in]
Button is installed on D3
LED is installed on D7

Program:

int button = 3;
int LED = 7;

void setup()
{
  pinMode(button, INPUT); //define button on INPUT devices
  pinMode(LED, OUTPUT);   //define LED on OUTPUT device
}

void loop()
{
  int buttonState = digitalRead(button); //read the status of hte button

  if(buttonState == HIGH) //also used (buttonState == 1)
  {
    digitalWrite(LED, HIGH); //also used digitalWrite(LED, 1)
  }
  else
  {
    digitalWrite(LED, LOW); //also used digitalWrite(LED, 0)
  }
}

Upload Verbose Message:

avrdude: verifying ...
avrdude: 1070 bytes of flash verified
avrdude: Send: Q [51]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]

avrdude done.  Thank you.

I have only had the LED from this program turn on twice, then reloading it ruins it.

SIDE NOTE

If I try and run Burn BootLoader I get this message-

avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino/hardware/tools/avr/etc/avrdude.conf"

         Using Port                    : usb
         Using Programmer              : stk500v2
avrdude: usbdev_open(): did not find any USB device "usb"

OK mystery solved!

I ended up getting Visual Micro Debugger plug-in for my Visual Studio 2013 since I am native .NET programmer. I could see that the code was indeed loaded onto the board and when I pressed the button it was indeed getting to the line of code for setting the digital LED to HIGH.

It was a very unfortunate case of trying different components and learning I actually had 3 dead LEDs and one bad cable. After getting functioning ones it's all good. :) unlucky me just had 4 bad parts in my kit.

Output from Visual Studio Debugging:

Legend:
line 12 = button state check
line 16 = button pressed turn on LED
line 20 = button not pressed turn off LED

=================OUTPUT====================
14:01:04.372 SeeedDuinoPlayground.ino, line 12  loop()
14:01:04.372 SeeedDuinoPlayground.ino, line 16  loop()
14:01:04.481 SeeedDuinoPlayground.ino, line 10
14:01:04.481 SeeedDuinoPlayground.ino, line 12  loop()
14:01:04.592 SeeedDuinoPlayground.ino, line 16  loop()
14:01:04.592 SeeedDuinoPlayground.ino, line 10
14:01:04.696 SeeedDuinoPlayground.ino, line 12  loop()
14:01:04.697 SeeedDuinoPlayground.ino, line 20  loop()
14:01:04.804 SeeedDuinoPlayground.ino, line 10
14:01:04.804 SeeedDuinoPlayground.ino, line 12  loop()
14:01:04.912 SeeedDuinoPlayground.ino, line 20  loop()


Wierd Issue with PWM pin I'm trying to run two of my motors through PWM. Here's my code -

#include <Servo.h>
int Lm = 11;
int Rm = 10;
int incomingByte = 0;
int pos = 0;
Servo myservo;
void setup() {
  pinMode(Rm, OUTPUT);
  pinMode(Lm, OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(2,OUTPUT);
  myservo.attach(3);
  Serial.begin(9600);

}

void loop() {
  blinkers();
  if (Serial.available() > 0) {
                incomingByte = Serial.read();
  }
  if(incomingByte == 49){
    analogWrite(Rm, 128);
    analogWrite(Lm, 128);
  }
   else if(incomingByte == 48){
    analogWrite(Rm, 0);
    analogWrite(Lm, 0);
    myservo.write(0);
  }
  else if(incomingByte == 50){
    analogWrite(Rm, 0);
    analogWrite(Lm, 128);
    delay(500);
    analogWrite(Lm, 0);
  }
  else if(incomingByte == 51){
    analogWrite(Rm, 128);
    analogWrite(Lm, 0);
    delay(500);
    analogWrite(Rm, 0);
  }
  else if(incomingByte == 52){
    for (pos = 0; pos <= 180; pos += 10) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 10) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);
  }
}
}

void blinkers(){
    digitalWrite(7, HIGH);
    digitalWrite(2, HIGH);
  delay(100);
  digitalWrite(7, LOW);
  digitalWrite(2, LOW);
  delay(100);
}

Now in this code... Lm, and Rm are my motors. The motor Lm runs perfectly fine, but Rm doesn't move at all. When I use digitalWrite instead, both motors work fine.

I tried running the motor in the exact same setup but this time with only the code for running the motor by PWM. The code was -

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

}

void loop() {
  analogWrite(10, 128);
  delay(100);
  analogWrite(10, 0);
  delay(100);

}

This code worked perfectly fine.

So clearly there is an issue in the earlier code but I can't figure out what. Everything is correct in that as well but the motor refuses to move...

Can anyone tell why is this happening?

It is a timer conflict.

The Servo reference says: "...use of the library disables analogWrite() (PWM) functionality on pins 9 and 10..."

This is a picture of the pinmapping of the Arduino Uno: PighiXXX - Uno.
Pin 9 en 10 uses OC1A en OC1B for PWM, that is Timer1. You can't use PWM on them when the Servo is used.
Pin 11 uses OC2A for PWM, which is Timer2.

I suppose it will work if you choose another PWM pin for analogWrite. Timer0 is used for millis and therefor the PWM frequency will be different (pin 5 and 6). That is mentioned in the analogWrite reference. In most cases that is not a problem.
Pin 3 is a normal PWM pin.

This is a common problem. The documentation is not always clear about the use of timers and other parts of the microcontroller. Many times the source code has to be read to see what is used. In the end, you need more experienced Arduino users to spot the conflict.


Storing value in EEPROM in Arduino Uno Hi I am a beginner in Arduino Uno. I wanted to store a value of 77880 in EEPROM and fetch it later. I made the code as follows to check my logic(I am using Arduino Uno) :
#include <EEPROM.h>
int addr = 0;
byte value;
void setup() {
  // put your setup code here, to run once:
  int val = 77880;
  EEPROM.write(addr, val);
  Serial.begin(57600);
}

void loop() {
  // put your main code here, to run repeatedly:
  value = EEPROM.read(addr);

  Serial.print(addr);
  Serial.print("\t");
  Serial.print(value);
  Serial.println();
  delay(1000);
}

but I am not getting the value of 77880 when I read the EEPROM address. instead I am getting a value of  56 in my serial output. Can anybody pls explain how should I implement the same?

EEPROM can only store the values 0-255 in any one address. That's the maximum range of an 8-bit value, and EEPROM "cells" are 8-bit in size.
You will have to split your value up into multiple 8-bit chunks and store each chunk at a different address - for example for 32-bit values you can use:
uint32_t val = 77880; // In hex is 0x13038
int addr = 0;
EEPROM.write(addr, val & 0xFF); // Stores 0x38 in address 0
EEPROM.write(addr + 1, (val >> 8) & 0xFF); // Stores 0x30 in address 1
EEPROM.write(addr + 2, (val >> 16) & 0xFF); // Stores 0x01 in address 2
EEPROM.write(addr + 3, (val >> 24) & 0xFF); // Stores 0x00 in address 3

Then to read you do the opposite and shift the values and OR them:
uint32_t val = (uint32_t)EEPROM.read(addr) |
               ((uint32_t)EEPROM.read(addr + 1) << 8) |
               ((uint32_t)EEPROM.read(addr + 2) << 16) |
               ((uint32_t)EEPROM.read(addr + 3) << 24);

Alternatively the EEPROM library has a "store anything" helper to do it for you:
EEPROM.put(addr, val);

That will store the variable val across enough cells to fit it (4 in the case of a 32-bit variable), so you must know not to write to the other cells used by it (0, 1, 2 and 3 in this case) or you will corrupt your data.
You recall it with:
EEPROM.get(addr, val);


Best way to ask Arduino for data from Python? I'm trying to send numerical data from inertial sensors from my Arduino to a Python script via serial (PySerial).
I found that if I continuously send the data from the Arduino without stopping, the serial buffer fills up quickly and the sensor measurements that the Python reads becomes delayed.
To fix this, I thought of having the Python script send over a transmit command to the Arduino when it needs data. I'm sending a char 't' to signify this command, but the delay between Python sending the command and the Arduino sending the data is too large.
I'm wondering if there's a 'proper' way of doing this, as I'm sure it's probably been done before?

This is not a complete answer to your problem, but currently you seem to have some misconceptions, that prevent you from pin pointing the actual problem.
The data transmission from the sensor, over the Arduino to your python script on the PC has multiple places, where a bottleneck can appear. The total data rate will then be at maximum as large, as the smallest bottleneck allows it to be.
First you have a potential bottleneck in the communication between sensor and Arduino. You haven't stated, what kind of IMU chip you have and how it communicates. Typical IMU chips like the MPU series are interfaces via I2C or SPI. SPI can be sped up rather greatly, while I2C is not that easy to speed up. But it depends greatly on the capabilities of the used chip. You can find information about that in the corresponding datasheet of the chip.

The next interface is the Serial (UART) interface between Arduino and PC. This interface has a fixed baudrate. When you use Serial.write() or its siblings, you simply fill the send buffer of the Serial library. The data will then be send out automatically at the correct timing for your baudrate. The transmission always happens, if the python script is reading or not. The transmission also happens, when the serial buffer of the script is full. The Arduino does not know about the buffer being full. So in this case the data is not delayed, but lost.

The last - and probably most important - potential bottleneck is how you read and send the data on Arduino and in the python script. Here I'm covering the Arduino side.
You should not use functions like Serial.readString(), as they work with a timeout, which will slow down your code drastically. Instead you should read the Serial data byte by byte into a buffer, delimiting your message with a special character (for example the newline character \n). You check, if there is any data Serial.available(), and if yes, you read one byte into a char array, which is your own buffer. You are doing that repeatedly, until you read the delimiting character. Then you process the complete message. That way will give you some important improvements:

You can do things in the meantime (for example reading new data from your sensor)
It works without any arbitrary timeout, thus not slowing down your code unnecessaryly
The delimiting character frames a full message, so that you can distinguish two different messages from each other and thus easier process them

Considering the above, you should make the requirements clearer:

How much latency between the actual sensor measurements and the receiving in the python script is ok for you, meaning: How old can the measurements be, that the python script gets? (You just stated, that it is too large, but you have not mentioned how large)

Do you need continuous data transmission, or just one or a few sets of the IMU data?

Then you can check for the needed speed and data rate. Check, if all involved interfaces and codes can really handle your requirements.
Also it would be easier for us to help you, when you show your current code in your question.


Why do I see error in this code NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_1KHZ);
AF_DCMotor motor2(2, MOTOR12_1KHZ);
AF_DCMotor motor3(3, MOTOR34_1KHZ);
AF_DCMotor motor4(4, MOTOR34_1KHZ);
Servo myservo;

boolean goesForward=false;
int distance = 100;
int speedSet = 0;

void setup() {

  myservo.attach(10);
  myservo.write(115);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
}

void loop() {
 int distanceR = 0;
 int distanceL =  0;
 delay(40);

 if(distance<=15)
 {
  moveStop();
  delay(100);
  moveBackward();
  delay(300);
  moveStop();
  delay(200);
  distanceR = lookRight();
  delay(200);
  distanceL = lookLeft();
  delay(200);

  if(distanceR>=distanceL)
  {
    turnRight();
    moveStop();
  }else
  {
    turnLeft();
    moveStop();
  }
 }else
 {
  moveForward();
 }
 distance = readPing();
}

int lookRight()
{
    myservo.write(50);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
}

int lookLeft()
{
    myservo.write(170);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
    delay(100);
}

int readPing() {
  delay(70);
  int cm = sonar.ping_cm();
  if(cm==0)
  {
    cm = 250;
  }
  return cm;
}

void moveStop() {
  motor1.run(RELEASE);
  motor2.run(RELEASE);
  motor3.run(RELEASE);
  motor4.run(RELEASE);
  }

void moveForward() {

 if(!goesForward)
  {
    goesForward=true;
    motor1.run(FORWARD);
    motor2.run(FORWARD);
    motor3.run(FORWARD);
    motor4.run(FORWARD);
   for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid loading down the batteries too quickly
   {
    motor1.setSpeed(speedSet);
    motor2.setSpeed(speedSet);
    motor3.setSpeed(speedSet);
    motor4.setSpeed(speedSet);
    delay(5);
   }
  }
}

void moveBackward() {
    goesForward=false;
    motor1.run(BACKWARD);
    motor2.run(BACKWARD);
    motor3.run(BACKWARD);
    motor4.run(BACKWARD);
  for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid loading down the batteries too quickly
  {
    motor1.setSpeed(speedSet);
    motor2.setSpeed(speedSet);
    motor3.setSpeed(speedSet);
    motor4.setSpeed(speedSet);
    delay(5);
  }
}

void turnRight() {
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(BACKWARD);
  motor4.run(BACKWARD);
  delay(500);
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
}

void turnLeft() {
  motor1.run(BACKWARD);
  motor2.run(BACKWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
  delay(500);
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
}

All of the errors I got were "NewPing does not name a type", "AF_DCMOtor does not name a type" and "motor<> was not declared in this scope". I don't see library includes; at least one for NewPing is needed. I don't know where AF_DCMotor is supposed to be declared but, as it is not declared as a type, it leaves all of the motor undefined. Those are the bulk (if not all) of the errors as the code stands now. Add the missing NewPing library do whatever you need to to define AF_DCMotor.


How to send information from a web-site to the arduino? I currently have an Arduino Mega + an Arduino Ethernet shield, I would like to know if it's possible to send data to the arduino from a web-site hosted on the shield itself. So that when someone press a Button on the web-site it sends a signal to the arduino to trigger an action. Could anyone kindly help me.

Yes of course!
First things first - Yes, it is possible to accomplish what you're thinking.
The idea is to create a server on the Ethernet Shield and open the webpage hosted by it on any device and based on the options selected on the web page we can trigger desired actions on the Arduino.
I've modified the web server code of Arduino built-in examples to match your requirements, just upload it and make necessary changes as required, here it is-
#include<SPI.h>
#include<Ethernet.h>

byte mac[] = {
   0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
 };

 IPAddress ip(192,168,1,199); // Any ip address not on your network.
 EthernetServer server(80);   // Port 80 is default for http.

  int led=2;

  String request;

  void setup(){
    Ethernet.begin(mac,ip);
    pinMode(led,OUTPUT);
    Serial.begin(9600);
   }

  void loop(){

      EthernetClient client = server.available();
  if(client)
         {
       Serial.println("Client is trying to connect......");
       while(client.connected())
       {
  if(client.available())
  {
    char c = client.read();
    request.concat(c);
    if(c=='\n'){
    Serial.print(request);
    if(request.indexOf("ON")>0){
      digitalWrite(led,HIGH);
      Serial.println("ON");
      }

      else if(request.indexOf("OFF")>0){
        digitalWrite(led,LOW);
        Serial.println("OFF");
        }
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    //client.println("Refresh: 5");  // refresh the page automatically every 5 sec
    client.println();

    client.println("<!doctype html>");
    client.println("");
    client.println("<title>LED</title>");
    client.print("<!DOCTYPE HTML>
LED ON

LED OFF

" );
    client.println("");
    client.stop();
    request="";

  }
  }
 }

    }

   }

This sketch will turn an LED on or off attached to digital pin 2.
You have to go to the IP address that you provide to the shield (192.168.1.199 in my case). You'll see 2 hyperlinks to switch on or off the led and that would pass a query which the Arduino looks for again and again in the loop and takes action accordingly.
Hope this helps, try this out, and do let me know the result.
NOTE
Make sure that you access the Ethernet Shield from a device within your LAN only otherwise you'll have to use port forwarding.


Atmega328 board output voltage I'm thinking about making my own "arduino" low power board but I have a question about the atmega328. Is the output voltage on the pins always 5v or it depends on the input voltage I gave to the atmega?

Thanks in advance.

It depends on the input voltage you give it.  If you run the ATMega328p at 3.3V then you get 3.3V out.  If you run it at 5V you get 5V out.

A word of caution about running at lower voltages:  The chip can't run as fast when it has a lower supply voltage - that's why you will see the 3.3V Arduino boards running at 8MHz (or 12MHz at a pinch).


Wiring diagram for Arduino to prevent relay firing on reboot I'm starting to explore using an Arduino to control a couple of switches programatically. I have read somewhere about relays firing during reboot due to floating inputs/outputs during the reboot phase.

What is the best way to ensure that a relay will not fire on a reboot?

Is there a simple wiring diagram to explain it? I am using an Arduino Uno and a Relay Module.

Any assistance would be greatly appreciated.

You can add a pull down/up resistor between the wire and ground/vcc so that when the arduino pin is set to high impedance during reboot the wire is pulled low/high as desired.


nrf24l01+ with antenna problem I just got 4 nrf24l01+ modules with the external antennas, but I'm not able to make them work.

I'm using arduino nanos and MySensors to create a gateway and a sensor.

The funny thing is that when I put a antenna nrf as the gateway and a pcb nrf as sensor, they work just fine, but the other way doesn't.

I also tried two nrfs as gateway and sensor, but the behavior does not look good.

What could it be? Wifi router interference? Channel? Baud rate? Data rate?

It's likely an issue related to the modules'  electric supply. The effects can be packet loss (even down to zero bps) or loss of communication with the module.

Two things have to be covered with the nRF modules for them to work:

current draw (i.e. power),
decoupling/filtering (i.e. bypass capacitors).

Since you don't mention specific devices, I'm assuming you refer to an 'antenna' module with SMA (or RP-SMA) connector.

The Nordic Semiconductor nRF24l01+ that is typically used in these modules has a maximum power consumption well below 100mW.

A module with power amplifier (PA) draws significantly more power than the nRF chip alone, the total power consumption will be larger than 100mW.

An Arduino can only supply power according to it's onboard regulator capabilities.
The Minis (and Micros) feature a smaller regulator that cannot drive both the Atmel AVR microcontroller and the PA.

Solution:

provide a separate 3.3V regulator for the nRF module(s),
place a capacitor directly at the modules' connector's supply pins.

Link:

https://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo#PP


How do I statements for the various conditions of this function? I am still new to Aduino and I am trying to use a library's example sketch but I don't understand the following part of the code. I want to trigger an led when the "Pressed" condition is fulfilled. Pardon my ignorance.

if (b != ClickEncoder::Open) {
Serial.print("Button: ");
#define VERBOSECASE(label) case label: Serial.println(#label); break;
switch (b) {
  VERBOSECASE(ClickEncoder::Pressed);
  VERBOSECASE(ClickEncoder::Held)
  VERBOSECASE(ClickEncoder::Released)
  VERBOSECASE(ClickEncoder::Clicked)

  case ClickEncoder::DoubleClicked:
      Serial.println("ClickEncoder::DoubleClicked");
      encoder->setAccelerationEnabled(!encoder->getAccelerationEnabled());
      Serial.print("  Acceleration is ");
      Serial.println((encoder->getAccelerationEnabled()) ? "enabled" : "disabled");
      setMode = true;
       value = 0;
    break;
}

}

You will have to explicitely expand the case ClickEncoder::Pressed. So instead of

VERBOSECASE(ClickEncoder::Pressed);

you should write something like

case ClickEncoder::Pressed:
    Serial.println("ClickEncoder::Pressed");
    digitalWrite(ledpin, HIGH);
    break;

Of course then you'll have to turn it off then, but.. Well, that's another problem


setting output analog/digital pin to ground So I need to automaically eject a CD from a Blu-Ray drive, I have a wire welded on the drive's card that if manually connected for a split second (pulse) to the ground of that same card on the drive, will eject the CD. Now in order to do that automatically I'm using an Arduino Nano and I connected that wire to an analog pin "d1" set its mode to Output and connected the grounds of both Arduino and drive together. Here's my code 1

int ds1 = A2; //pin that indicates the existence of the CD inside the drive if HIGH and its inexistance otherwise
int d1 = A3;  //pin connected to the wire that if connected to ground ejects the CD

void setup() {
  Serial.begin(9600);
  pinMode(ds1, INPUT);
  pinMode(d1, OUTPUT);
  while((!analogRead(ds1))) //if the CD isn't inside the drive wait
  {}
}

void loop() {
  analogWrite(d1,0); //eject CD
  delay(500);
  while(!analogRead(ds1)) //if the CD isn't inside the drive wait
  {}
  delay(1000);
}

I'm thinking that maybe setting the pin to 0 doesn't necessarily mean I connected it to the gnd, it's just a possibility if you see anything wrong with the code or have any suggestion please help me

Yes, setting a pin to OUTPUT and setting it LOW effectively connects the pin to ground (via a few ohms of resistance).

There's a couple of things wrong with your code, though, which you should address:

Use digitalWrite() not analogWrite().

analogWrite(pin, 0) is effectively the same as digitalWrite(pin, 0), but it's ambiguous to someone reading your code.

You never "release" the pin, so once it goes LOW it stays LOW.  You should emulate open drain by setting it to INPUT when not using it.
You should get into the habit of putting repeated code into functions to make it more understandable what's going on.

For example:

void setup() {
  Serial.begin(9600);
  pinMode(ds1, INPUT);
  pinMode(d1, INPUT);
  waitForCD();
}

void loop() {
  triggerEject();
  waitForCD();
  delay(1000);
}

void triggerEject() {
  pinMode(d1, OUTPUT);
  digitalWrite(d1, LOW); // Press the button
  delay(100); // This is how long the button is pressed for
  pinMode(d1, INPUT); // Release the button
}

void waitForCD() {
  while(!analogRead(ds1)) //if the CD isn't inside the drive wait
  {}
}

!analogRead(ds1) will only ever be true if the voltage at pin A2 is exactly zero volts. If you really want to read an analog voltage here you should find a threshold value that the value is compared to:

while (analogRead(ds1) < 100)) {}

Or it may be that you actually want to use digitalRead()...


Trigger countdown with 433MHz transmission I would like to use an arduino to read 433 MHz transmission from multiple Soil Moisture Sensors. Since I can never be sure all transmissions reach the receiver I'd like to set a countdown from the moment the first transmission is received. If another transmission is received, the countdown starts again.
After a defined amount of time (e.g. 10 Minutes) without any more signals or if all signals have been received (e.g 4 Sensors) the receiving unit should stop and come to decision based on the data it got to the point.

For transmitting and receiving I am using the <RCSwitch.h>library.

The loop of the receiving unit and one Sensor looks like this:

#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();
void Setup(){
Serial.begin(9600);
mySwitch.enableReceive(4);
}
void loop() {
if (mySwitch.available()) {
int value = mySwitch.getReceivedValue();

if (value == 0) {
  lcd.clear();
  Serial.print("Unknown encoding");
  }
  else {
  Serial.print(mySwitch.getReceivedValue());
  Serial.print("%");
}

The full code includes some differentiation mechanism for all sensors but I figured that might not be relevant for my question.

Question:
What's the best way to do this without a real time clock module. As far as I know I can't wait by using delay(...)since then I won't receive any data while the processor waiting.

You say The full code includes some differentiation mechanism for all sensors so I'll assume there's some function GetSensorId() that returns 0 to NUM_SENSORS - 1.

So, you need to keep track of a) how many sensors have reported in and b) time since the last report. You can't just count how many sensors have reported in since there may be a chance one could report in more than once. So I would use an array:

// Assume you never receive 0 from sensor.
const int NO_DATA = 0;
const int NUM_SENSORS = 4;
int sensor_data[NUM_SENSORS];

void setup() {
    // Initialize array
    for (int i = 0; i < NUM_SENSORS; i++) {
        sensor_data[i] = NO_DATA;
    }
}

Also, a variable to keep track of time of last message:

uint32_t last_message_time = 0;

So, in loop():

void loop() {
    // Check for data
    if (mySwitch.available()) {
        int value = mySwitch.getReceivedValue();
        if (value == 0) {
            lcd.clear();
            Serial.print("Unknown encoding");
        }
        else {
           // Determine which sensor sent the data
           int sensor_id = GetSensorId();
           Serial.print(value);
           Serial.print("%");
           // Save the data and the time of the message
           sensor_data[id] = value;
           last_message_time = millis();
       }
    }
    // See if all sensors reported
    byte sensors_reported = 0;
    for (int i = 0; i < NUM_SENSORS; i++) {
        if (NO_DATA != sensor_data[i]) {
            sensors_reported += 1;
        }
    }

    // When 0 sensors have reported in, do nothing
    if (0 != sensors_reported) {
        // Otherwise, at least one sensor
        // check the time
        uint32_t elapsed = millis() - last_message_time;

        // If have all data or time's up, do something
        if (NUM_SENSORS == sensors_reported || elapsed > SENSOR_TIMEOUT) {
            // Do something

            // Reset state
            for (int i = 0; i < NUM_SENSORS; i++) {
                sensor_data[i] = NO_DATA;
            }
        }
    }
}


double type sensor data is not displayed on bluetooth terminal app on phone Hi I am working on a project in which I am supposed to tell if a person is running/standing/walking and going upstairs/downstairs or he is on straight road. The person will carry a arduino uno module to which gps,bluetooth and altitude sensor is attached. Also I am trying to send my phone his speed and current altitude he is experiencing using HC-05 bluetooth module. I am sure that there is no problem with altitude sensor. Also I must note that my gps module(GY_NE06MV2) is not acting proper when it comes to speed of the person. I believe this is because I experimented in my house and not outside. The problem is that I cannot see speed and altitude data on bluetooth terminal app"ArduTooth" on my phone. It is just like a blank space which should have been my data. I am presenting my code which is not very long and I hope you could help me get through this.
#include <SoftwareSerial.h>
#include <TinyGPS++.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

TinyGPSPlus gps; //gps object to be used
SoftwareSerial BTserial(10, 11); //bluetooth serial connection
SoftwareSerial gps_serial(4,3); //gps serial connection
Adafruit_BME280 bme; //altitude measuring sensor object

#define SEALEVELPRESSURE_HPA (1011) //sea level pressure in Turkey/Eskisehir

double speed = 0; //speed of a moving body
double current_altitude = 0;
double previous_altitude = 0;

void setup() {
Serial.begin(115200); // serial connection to computer
BTserial.begin(9600);
gps_serial.begin(9600);
bme.begin(0x76);

delay(3000);

previous_altitude = bme.readAltitude(SEALEVELPRESSURE_HPA);

}

void loop() {
//data from gps device is fed to gps object
while (gps_serial.available() > 0){
    gps.encode(gps_serial.read());
}

if(gps.speed.isValid()){
speed = gps.speed.kmph();
BTserial.write(speed); // this is where the problem-1 is, this data is not shown on mobile phone
bluetooth terminal application
BTserial.write(",");

  if(speed <= 5 && speed > 0.5){
    BTserial.write("walking");
    BTserial.write(",");
  }
  if(speed <= 0.5){
    BTserial.write("standing");
    BTserial.write(",");
  }
  if(speed > 5){
    BTserial.write("running");
    BTserial.write(",");
  }

  }else{
    BTserial.write("m.s.n.n"); //stands for "moving status not known"
    BTserial.write(",");
  }

current_altitude = bme.readAltitude(SEALEVELPRESSURE_HPA);
BTserial.write(current_altitude); //this is where problem-2 is, this data also is not displayed
on phone
BTserial.write(",");
//this part determines either the body goes upstairs or downstairs or he is on straight road
if(current_altitude - previous_altitude >= 0.7){
  BTserial.write("going ups.");
  previous_altitude = current_altitude;
}
if(previous_altitude - current_altitude >= 0.7){
  BTserial.write("going downs.");
  previous_altitude = current_altitude;
}
if((current_altitude - previous_altitude <= 0.3) || (previous_altitude - current_altitude <=
0.3)){
  BTserial.write("on s.r");
  previous_altitude = current_altitude;
}
BTserial.write(";");

delay(1000);

}

I must note that purpose of BTserial.write(",");  is that every seperate entry sent to phone via bluetooth must be seperated by ",".

You can convert you double data to string type.this trick may help. And you also can just sent a byte for different positions and decode them in app.


Motor driver not able to drive motor in reverse direction In my recent project, I'm using DC motor driver 24V 20A[RKI-1340].

Motor Driver

After reading the manual of this I figure out information for this motor driver.
Basically, this motor driver has 5 pins. Each has own functionality.

  (1) 5V : Regulated 5V output from motor driver board (maximum 50mA
  supply)

  (2) BRK : Breaking input to halt the motor in operations when 5V
  (logic high)

  (3) PWM : Pulse Widht Modulation input to control speed of motor
  (recommended freq 20Hz to 400Hz)

  (4) DIR : Pulled down to GND Forward by default and Backward when 5V
  (logic high)

  (5) GND : Connect to GND on controlling board

Now, I connect this motor driver to my Arduino. My connection is like below:

  Motor Driver : Arduino

  5V - No connection with Arduino

  DIR ---> Pin 4

  PWM ---> Pin 5

  BRK ---> Pin 6

  GND - No connection with Arduino

And my code is like below:

const int kPinDIR = 4;
const int kPinPWM = 5;
const int kPinBRK = 6;

void setup()
{
  pinMode(kPinDIR, OUTPUT);
  pinMode(kPinBRK, OUTPUT);
  pinMode(kPinPWM, OUTPUT);
}

void loop()
{
  digitalWrite(kPinDIR, HIGH);   // Case 1
  digitalWrite(kPinBRK, LOW);

//  digitalWrite(kPinDIR, LOW);  // Case 2
//  digitalWrite(kPinBRK, HIGH);
//
//  digitalWrite(kPinDIR, LOW);  // Case 3
//  digitalWrite(kPinBRK, LOW);
//
//  digitalWrite(kPinDIR, HIGH); // Case 4
//  digitalWrite(kPinBRK, HIGH);

  analogWrite(kPinPWM, 255);
}

As you can see that, I tried out 4 different case to run motor. But motor run only for first two case(case 1 & 2) and direction of rotation is same. And in other two case(case 3 & 4) motor is not rotating.

I don't understand that thing why case 1 and case 2 give same output. If I tried out logic according manual description means according manual DIR pin change the direction of motor's rotation. According that If I provide LOW logic(GND) to DIR pin then motor rotating in one direction and but If I provide HIGH logic(5V) to DIR pin then motor is not rotating. I tried every case(already written in my code) but motor is still rotating in same direction.

And here I provide supply to motor driver by regulated power supply. And for Arduino, it take supply through it's cable(cable is connected to LAPTOP).

Actually, I am trying to run Peltier module using this motor driver. I want to change Peltier's polarity using this. So, first I tried out with motor then If I succeed then I tried this one to Peltier. I think I have to connect GND of Motor Driver to Arduino's GND but I think it will my Arduino. I'm not sure about this GND connection between Motor Driver and Arduino. Please suggest me.

EDIT 1: My wiring is look like this.

simulate this circuit – Schematic created using CircuitLab

The motor driver's GND does need to be connected to the Arduino's GND so that the signal loop is complete. This won't break the Arduino.


Arduino-IDE "while (!Serial)" I have a Question regarding Arduino IDE:

Many old Arduino setup examples states that the Serial.begin() function always should begin with :

Serial.begin(9600); // (or 115200)

while (!Serial)
 {
   ; // Wait for serial to connect
 }

Now I have read a lot of comments saying that this "Wait-function" is no longer necessary ??

Is this an old routine, that's no longer necessary, or is it still important ???

That function is not obsolete. However, there is gratuitous use of it where it's not really needed.

The usage of the function that you alude to grew from the desire to make ATMega32U4-based boards (such as the Leonardo) which have a native USB interface act similar to the ATMega328P etc boards.

When you open the serial port on an Uno, for example, the main MCU is reset and the sketch runs from the start.  When you do the same on a Leonardo that doesn't happen. So by adding that code snippet to the beginning the sketch is paused until the serial port is opened.  This makes it appear that the board has been reset and the sketch is running afresh, like an Uno - but it isn't.

Placing that while loop at the start of your sketch without thinking about the consequences means that your sketch may never run. If a serial connection is required for your program then that's not such a problem. However, if all you're using the serial for is debugging, then as soon as you try and use your sketch without the computer opening the serial port it will fail.

So I would recommend not using that while loop unless you know that you want the effects that it provides.  That is, stalling the sketch until the serial port is opened by the computer.


Read and write on the same node (central) using an RF24 network on Arduino I want to send and receive on the same node using the RF24Network library, but I'm unable to do so even when I use radio.StopListening().

Here is the code:

#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(9,10);
RF24Network network(radio);
struct payload_t{unsigned long int code; unsigned long int message;};

void setup(void) {
  Serial.begin(9600);
  SPI.begin();
  radio.begin();
  radio.setPALevel(RF24_PA_MAX);
  radio.setDataRate(RF24_250KBPS);
  radio.setAutoAck(false);
  network.begin(108, 0);
}

void loop(){
  network.update();
  RF24NetworkHeader header;
  payload_t payload;
  if(network.available()) {
    network.read(header, &payload, sizeof(payload));
    Serial.println(payload.message);
    // I WANT HERE TO SEND BACK TO THE TRANSMITTER but I'm unable to do that
    radio.stopListening();
    payload_t payload = { 2000, 15444452 };
    RF24NetworkHeader header(2);
    network.write(header, &payload, sizeof(payload));
  }
}

Second Node:

#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(9,10);
RF24Network network(radio);
struct payload_t{unsigned long int code; unsigned long int message;};
firstExec = 1;

void setup(void) {
  Serial.begin(9600);
  SPI.begin();
  radio.begin();
  radio.setPALevel(RF24_PA_MAX);
  radio.setDataRate(RF24_250KBPS);
  radio.setAutoAck(false);
  network.begin(108, 2);
}

void loop() {
  network.update();
  if(firstExec) {
    radio.stopListening();
    payload_t payload = { 2000, 5555555 };
    RF24NetworkHeader header(0);
    network.write(header, &payload, sizeof(payload));
    radio.startListening();
    firstExec = 0;
  }
  RF24NetworkHeader header;
  payload_t payload;
  if(network.available()) {
    network.read(header, &payload, sizeof(payload));
    Serial.println(payload.message);
  }
}

The library says you must include network.update() in loop() for the nodes to be in sync. Place that call at the top of loop() in both nodes.


How to differentiate between 2 Micros on Linux I have 2 Arduino Micro based devices that I want to use on my Ubuntu Linux machine.  I need them to have unique serial ports.  Unfortunately, both have the same serial number which makes identification through udev rules difficult (if not impossible).

This is the serial number that I get for both:

$ udevadm info -a -p  $(udevadm info -q path -n /dev/ttyACM0) | grep -i serial
  ATTRS{serial}=="0000:00:14.0"

Is there any way to manually set the serial number on an Arduino Micro?  Or is there any other unique identifying properties I can use for udev rules?

Typically, I do something like this in my /etc/udev/rules.d/99-usb-serial.rules file:

SUBSYSTEM=="tty", ATTRS{product}=="Arduino Uno", ATTRS{serial}=="64936333936351911191", SYMLINK+="MyDevice"

Side note: I also have a Due, that has the same serial number as the Micros, but since ATTRS{product} is different, I can differentiate it.

The USB VID, PID and Serial Number are all programmed into the chip when you upload your sketch.  The VID and PID are tied to the board, and the serial number is always the same regardless of which board.

So no matter which board you program it will get the same details as any other board of the same kind.

There's no option to change the serial number (there is, IIRC, actually no serial number defined) but the VID and PID are provided as a pair of macros on the compilation command line: USB_VID and USB_PID.

So you could (cheakily) create a new board definition (based on the existing Micro one) that is "The other Micro" and provide a different (unofficial) PID to that board.  You can then differentiate the two boards in udev using the VID/PID combination.

Of course, you have to then ensure that you have the right board selected when you program them, and the act of entering the bootloader on the "other" board would revert back to the old PID which is programmed into the bootloader, but I'm sure you can cope with that.


Background "static" on side of TFT screen? I recently bought an XC4629 128x128 TFT screen and noticed that failing to initialise a background for the screen produced this RBG static.

A red line drawn on the screen without a background:

The problem, however, is that when I did initialise a background, the "static" remained on 3-4 pixels down the side of the screen:

Here is the code I used:

 #include <TFT.h>
 #include <SPI.h>

 #define CS   10
 #define DC   9
 #define RESET  8

 TFT myScreen = TFT(CS, DC, RESET);

 void setup(){
   myScreen.begin();
   myScreen.background(0,0,0);
 }

 void loop(){
   myScreen.stroke(255, 0, 0);
   myScreen.line(0, 128, 128, 10);
 }

Is this a problem with the screen itself? I have searched around the internet and have found no similar issues. Due to the behaviour it seems like an code issue but I have made it as simple as possible and experimented and only found it goes away if I remove the signal and just have the screen on backlight only. I also double checked that the wiring was all in the correct slots (both referencing the code and the datasheet for the screen).

Many thanks in advance.

It will be a problem with the library you are using. Not all screens that use the same CoG are wired in quite the same way. Often a CoG that supports a larger number of columns is used with a screen that doesn't have that many columns (132 in this case), and the actual screen is placed at an offset within the available columns, and it's up to the manufacturer of the screen where that offset is.

So the library has to initialize the CoG with where the screen actually is within its physical column range, and your screen is different to what the library is expecting.  Looking at the TFT library bundled with the IDE most screen configurations appear to impose a couple of pixels offset in the columns, which you don't want.

I would suggest investigating other TFT libraries, such as UTFT, which may give better control over screen parameters.


Waking Arduino from sleep by holding button for more than 3 seconds I am working on a battery powered Arduino project, where I need to put a standalone Arduino in sleep mode (to save some battery).

My aim is to put Arduino in sleep mode by holding a button for 3 seconds or more on pin 2 (hardware interrupt) and wake it up by holding the same button by 3 seconds or more.

I can put the Arduino to sleep by holding button more than 3 seconds, but I can't wake it from it by holding the button for 3 seconds.

Below is my code:

#include <avr/sleep.h>
const int led1 = 44;
const int led2 = 45;
const int led3 = 46;
const int usbState = 12;
float pressLength = 0;
const int button = 2;
int optionOne = 100;
int optionTwo = 3000;

void setup() {
  pinMode(button, INPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(usbState, INPUT);
  Serial.begin(9600);
}

void loop() {
  while (digitalRead(button) == LOW) {
    delay(100);
    pressLength = pressLength + 100;
    Serial.print("ms-");
    Serial.println(pressLength);
  }
  if (pressLength >= optionTwo) {
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
    sleepNow();     // sleep function called here
  } else if (pressLength >= optionOne) {
    digitalWrite(led1, HIGH);
    digitalWrite(led2, HIGH);
    digitalWrite(led3, HIGH);
    while (1) {} //Keeps LEDS HIGH
  }
}

void sleepNow() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable(); // enables the sleep bit in the mcucr register
  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
  sleep_mode(); // here the device is actually put to sleep!!
  // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
  while (digitalRead(button) == LOW) {
    delay(100);
    pressLength = pressLength + 100;
    Serial.print("ms-");
    Serial.println(pressLength);
  }
  if (pressLength >= optionTwo) {
    SleepNow(); //Back to sleep fucntion
  } else if (pressLength >= optionOne) {
    sleep_disable();
    // first thing after waking from sleep: disable sleep...
    resetFunc();//Resetting
  }
}

void wakeUpNow() {
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
}
void(* resetFunc)(void) = 0;

Please help. Thanks.

You won't manage it without external circuitry.

The problem is the Arduino has to be awake to know you held the button for 3 seconds. You can only wake immediately you press the button. However you could then sleep again if the button is released within 3 seconds.

For external circuitry, you would need to arrange to charge (or discharge) a capacitor slowly through the button so that it reaches a threshold after 3 seconds and that threshold triggers the input to the Arduino. A HIGH input on the Arduino is 0.6×Vcc, so 3.3V for a 5V Arduino. If you arrange it that the capacitor reaches 3.3V after being charged for 3 seconds the input will see it at the right time.

simulate this circuit – Schematic created using CircuitLab

In this circuit, R1 and C1 form an RC network that charges the capacitor through the switch. C1 and R1+R2 form an RC network that discharges the capacitor all the time, so it is discharged when you release the button.

Discharge time will be slightly longer than charge time owing to the addition of R1 + R2.

To calculate the charge time, you can use T=RC which is how long (in seconds) it takes to charge the capacitor up to 63.2% of the supply voltage. That's fractionally over the 60% that the HIGH threshold is, so that's fine.

If you want T=RC to equal 3 seconds, you can rearrange the formula to suit your components. For instance if you have a 1000µF capacitor available you can rearrange to R=3/0.001 = 3kΩ. So a common 3.3kΩ resistor and 1000µF capacitor would give you (3300 × 0.001) 3.3 seconds.

R2 wants to be small enough that it doesn't slow down discharge too much, yet high enough that it doesn't draw too much current. Using about 10% of R1 is reasonable (330Ω), so with a 3.3 second charge time that resistor would increase the discharge time by 0.33 seconds.

This method is basically a very extreme form of debouncing.


Question about browsing the web using arduino I have got an arduino, a TFT touch screen and a WIFI module. The question is can i visit a specific web site and display it on that screen and interact with it.

You just have to install Chromium and call the desired page.

No, just kidding. I don't think you will ever fit a parsing and rendering engine on an arduino. Chromium for example takes about 150MiB of storage and depending on the opened page hundreds of MiB of RAM. Both of which is multiple orders of magnitude larger than the Arduino has to offer.

You might want to consider going to use a SBC like the Raspberry Pi for such usecase.

Alternatively you can query the data over network and write your own rendering code for the TFT display.


Arduino Blink two LEDs without Delay(amount of repetitions) Arduino community.  I have had experience with Arduino for 3 years now and have finally come to the conclusion to get rid of the delay function entirely.

Below is the code to blink two LEDs a complete 10 times.  The problem is that the setup() doesn't repeat like a loop(), which means it doesn't last a long enough to find a time difference between PreviousMillis and CurrentMillis because it runs once; thus, defeating the idea of blinking a LED in the setup().  But, I have researched ways to imitate the loop() with while loops; I have used Adafruit's method to spice things up(Constructors and classes!),
https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview.

But I need a little help because it doesn't work, instead, it blinks forever(Mission half-complete =)).

Notice how I have used while loops in the Update(), which is located within the Flasher Class, to mimic a loop() until the condition becomes true.

The problem is, I don't know why this code doesn't work and what to do from here.

The ultimate goal is to blink the LEDs at pin 12 and pin 13 a total of 10 Times, instead of repeatedly blinking for an eternity.  I am using an Arduino Uno R3 and a Serial baud rate of 115200.

Ignore what I did in the loop().  It's the same function as the setup() code, instead, the led blinks an eternity (unfortunately), when a value of "1" is typed.

    class Flasher{
    // Class Member Variables
    // These are initialized at startup
    int ledPin;      // the number of the LED pin
    long OnTime;     // milliseconds of on-time
    long OffTime;    // milliseconds of off-time

    // These maintain the current state
    int ledState;                 // ledState used to set the LED
    unsigned long previousMillis;   // will store last time LED was updated
    unsigned long currentMillis = 0;

  public: Flasher (int pin, long on, long off)
{            // Constructor - creates a Flasher
    // and initializes the member variables and state

      ledPin = pin;
      pinMode(ledPin, OUTPUT);

      OnTime = on;
      OffTime = off;

      ledState = LOW;
      previousMillis = 0;
    }

    void Update(int a){
      // check to see if it's time to change the state of the LED
      for (int i = 0; i < a; i++) {
        while ((currentMillis - previousMillis <= OnTime) || ((currentMillis - previousMillis <= OffTime))) {
          currentMillis = millis();

          if ((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
          {
            ledState = LOW;  // Turn it off
            previousMillis = currentMillis;  // Remember the time
            digitalWrite(ledPin, ledState);  // Update the actual LED
          }
          else if ((ledState == LOW) && (currentMillis - previousMillis >=OffTime))
          {
            ledState = HIGH;  // turn it on
            previousMillis = currentMillis;   // Remember the time
            digitalWrite(ledPin, ledState);   // Update the actual LED
          }
        }
      }
    }
};

Flasher led1(12, 100, 400);
Flasher led2(13, 350, 350);

void setup(){

  Serial.begin(115200);
  led1.Update(10);

}

void loop(){

   /* if (Serial.available()) {
      String str = Serial.readString();

      if (str.substring(0, 1).equals("1")) {
        led1.Update(10);

      }
  }*/
}

For such a simple task, the code is very complex.

First, write a piece of code that blinks the LEDs if sufficient passage of time has been met.

You can implement a blink counter, either in the main loop or the blink routine mentioned earlier.

Should be fairly simple.

edit: here is how I would have implemented it.

//blink the led for a given number of times
//cnt: number of times of the blinks needed
uint8_t led_blinky(uint8_t cnt) {
    static uint8_t led_cnt=0;       //blinky count
    static uint32_t millis_prev=0;  //previous millies

    if (led_cnt>=cnt) return led_cnt;   //return blink count
    if (millis() > millis_prev + LED_ms) {    //enough time has passed
        millis_prev += LED_ms;                      //update the time
        digitalWrite(LED, (digitalRead(LED)==HIGH)?LOW:HIGH);       //flip led
        led_cnt+=1;                 //increment the led count
    }
    return led_cnt;                 //return blinky count
}

the code itself is fairly self-explanatory -> the only (marginally) tricky part is how it maintains timing accuracy over a long period of time. in this particular implementation, the test is done inside the led_blinky() routine so it is self-contained -> it does return the number of blinks that have been executed.

Here is the execution of performing 100ms blinks 4 times:


Arduino resets my MacBook Pro Every time I connect the Arduino Uno to the Mac through USB port, the Mac restarts. Why is this happening? How can Arduino make such a sophisticated machine reset? This also happens with my ESP12E Node MCU.

It is almost certainly a device-driver issue. Since Arduinos are probably a little way down the pecking order for things that Apple is interested in, they probably don't test as extensively as (say) printers.

  How can Arduino make such a sophisticated machine reset?

Device drivers would operate with elevated privileges, because they need to control, well, devices, like hard disks, printers, etc. If one has a programming error (like dereferencing a NULL pointer) then it could crash the whole operating system.

I suggest you look at this page: IDE 1.6.12 released with Sierra support and more

It says there:

  A new version of the Arduino IDE (1.6.12) supporting OSX Sierra is available for download! All OSX users updating to Sierra are invited to also update the IDE to avoid crashes when uploading sketches.

This may or may not help. They seem to be suggesting that the IDE crashes rather than the Mac, but it could be worth trying.

There are some posts on macOS Sierra Usb Serial Crash which seem relevant:

  I need to use a arduino nano and my Mac with mac os sierra is rebooted when i plug in the arduino

It sounds like the CH340 chip set used on clone Arduinos is causing this.

A suggested new device driver fix is at ch340g-ch34g-ch34x-mac-os-x-driver


Missing Libraries make no sense I've never much issue importing a library to my master sketchbook location, restarting Arduino, then using the library examples. Today is a different story:

I'm loading RCLib which is part of this ArduinoLibraries family
RCLib requires PinChangeInt

So everything is in my sketchbook location right? Arduino > Preferences > Sketchbook Location

Still I'm getting compiler errors about missing libraries:

/Users/Jackson/Documents/Arduino/ArduinoLibraries-master/RCLib/Examples/Maga6ChanelsA8_A13/Maga6ChanelsA8_A13.ino:7:86: fatal error: PinChangeInt.h: No such file or directory
 #include "PinChangeInt.h"

I've even tried #include <PinChangeInt.h> Which makes more sense since this is a system library.

What is going on here?

The sketch I'm trying to run:

/**This is an example of using the RCLib with a mega and pinchangeint
 * This example isprovided as is by Jantje
 * Congratualtions, constructive feedback and I like it can be send to eclipse@baeyens.it
 **/

#define NUM_RC_CHANNELS 6 //You need to specify how many pins you want to use
#include "PinChangeInt.h"  //If you need pinchangeint you need to include this header
const uint8_t RC_Channel_Pin[NUM_RC_CHANNELS]={
  A8,A9,A10,A11,A12,A13};//Here I specify I want to listen to pins A8 to A13 of my mega

uint16_t RC_Channel_Value[NUM_RC_CHANNELS]; //This variable will contain the values read from the RC signal
#include "RCLib.h" //This include needs all declarations above. Do not try to move it up or it won't compile

Arduino v1.6.9 | OSX 10.11.4

I had downloaded PinChangeInterrupt through Arduino

Sketch > Include Library > Manage Libraries... > Filter your search... > PinChangeInterrupt > Install

I thought this is all I needed but I was wrong. This differs from the popular PinChangeInt library. Ultimately the file names where slightly different which is why my file was showing as missing. I found this out by manually looking at the file names in the library I was trying to used and comparing them against my includes.


Arduino Mega - Multithreaded (run two loops simultaneously) I am new to Arduino and I am not sure about how to get two loops run parallel to each other. I have tested the individual loops and both of them work perfectly before I combined them together.

One loop will take input from the LCD touchscreen. One loop will take input from vibration sensor which will determine the state (on/off) of LED. Once the LED is turned on, it has to stay at the ON state for 3 seconds before switching to OFF state.

The problem I am facing is that when the LED is triggered to ON state by vibration sensor, I have to wait 3 seconds for the input from LCD to get processed. Is there any way I can combine these two loops in such a fashion that I run them simultaneously, i.e. run two inputs together?

You can combine the 2 programs into 1 program.  But when you start wanting to do multiple things at once then you can't have any code that "blocks" and waits to finish before letting the next thing happen.  The Arduino has a single core, it can't do multithreading.  But if you write non-blocking code you can make things appear to happen at the same time.  I imagine the problem with your code now is that you have probably used the delay function.  That function blocks, so nothing else can happen while the delay is running.  Instead you have to use millis to record the time and periodically check against that time to see if it is time to take the next step instead of calling a delay to wait for the next step.  See the "Blink Without Delay" example that comes with the IDE and any of the multitude of tutorials about it on the web to see how it works.


Is it possible to upload a file with GPS values onto my arduino? I am absolutely new at arduino but ok with writing code. I am trying to upload 20 points of interest lat/long as a static file that sits on my arduino. Then I want to use my GPS sensor and a function which uses the haversine formula to constantly measure distance between all 20 points and the GPS data from the arduino and output the distance to the nearest point on an LCD screen.

I cannot figure out how to store and reference that list of GPS points of interest.

The Arduino does not have a file system per-se, to which you could upload files, unless you create the code that does that. There is "EEPROM" space on the Arduino processor that can hold 1024 bytes of data and survives power-cycles. That should be sufficient to hold 20 lon/lat pairs of sufficient precision.

As for how to get the waypoint data onto the Arduino, you could transfer them over the serial port from your computer, either by manual entry from your computer over the serial monitor of the Arduino IDE or by writing a script in Python or some other language to read the waypoint file and transmit the data according to the protocol you invented.

There are are also SD Card peripherals you can add to an Arduino, so you could potentially just load the waypoint file onto the SD Card from your computer, and then insert the card into the SD Card reader on the Arduino and have it read the data from there.


DS18B20 - Temperature a bit off? I'm trying to measure the temperature using a DS18B20 sensor. I'm using the DallasTemperature and OneWire Libraries. The sensor is connect in Pin 10 with a 4k7 resistor between VDD and DQ (actually I'm using 4x 1k and 2x 330 ohms) as so:

Here's the code I'm using:

#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 10

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

float celsius;

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

  sensors.setResolution(12);

  sensors.begin();
}

void loop(void) {
  sensors.requestTemperatures();
  celsius = sensors.getTempCByIndex(0);

  Serial.println(celsius);
}

The sensor is outputing values close to the actual temperature (measure with a mercury thermometer), but a bit off.

Example:

Sensor Temperaute: 34.44°C
Thermometer Temperature: ~32°C

Why is that? And how can I fix it?

When the wires to the DS18B20 are short, you can use a 10k resistor as well.

The DS18B20 is accurate. If you have connected it wrong and it became very hot, then it might be damaged. But normally it is always accurate.

Many report that the DS18B20 returns a high temperature, and the cause is often something nearby that makes the DS18B20 warmer. For example an Arduino board (with a hot voltage regulator) or a computer screen or a certain air flow of warm air or even very dim sunlight. A normal thermometer does not do that, but the DS18B20 is highly influenced by warm things nearby.

Some temperature sensors have a problem with self-heating. You could add a delay of 5 seconds in the loop function, to see if that makes a difference.

To be sure you can put it in distilled water at sea level at 0°C (water and ice cubes) and 100°C (boiling water).

The picture uses pin 2 and the sketch uses pin 10. I assume that is a mistake.


High Precision Temperature Sensor LMT70 connection to arduino mega How can I connect an LMT70 temperature sensor (4Pins) to Arduino Mega board for atmospheric temperature measurement. LM35 sensor has got only 3 pins and connections are known. But LMT70 high precision sensor got 4 pins. How to connect it to arduino mega board
Please help.
Thank you.

Every electronics component has a document that describes it. It is called a "datasheet".

This is the page for the LMT70: ti.com LMT70
The red text is for the datasheet as pdf document, or else you can use the tab "Online datasheet", and the datasheet can also be found under the tab "Technical documents".

According to the datasheet it works with 5V, you can use it with the Arduino Mega (which is a 5V Arduino board). Connect the analog output of the sensor to an analog input of the Arduino Mega.

If you don't use the T_ON, then the datasheets says: "Tie this pin to VDD if not used". That means you can connect T_ON to 5V.

Do you have the chip (the sensor) only, or do you have a module with the sensor on it ?

Since the sensor has an anlog output, the accuracy depends not only on the sensor but also on the Arduino and the Arduino voltage reference. If you need a highly accurate temperature measurement, then you better buy a digital temperature sensor. For example the Si7051.

I suggest to use the 2.56V Internal Analog Voltage Reference.
The sensor has 1375.2mV output at -55°C and 302.8mV at 150°C.

const float aref = 2.56;  // adjust it to the actual AREF voltage
int adc_value = analogRead(A0);
float voltage = float(adc_value) * aref / 1024.0;

float t1 = voltage - 302.8;  // get rid of voltage offset
float t2 = t1 * (150.0 + 55.0) / (1375.2 - 302.8); // match range
float temperature = 150 - t2;  // negate and offset.

When you measure the AREF pin with a good multimeter and fill in the correct voltage in the calculation in the sketch, then you can get 1°C accuracy for the temperature. Perhaps you can get near 0.5°C accuracy, but no more. The sensor is more accurate than the Arduino Mega.


How to interrupt a Timer to Change position along a Colour Cycle I want to have a loop of 4 colours which runs constantly (i.e. red -> green -> blue -> white) each of the colours having their own LED and pin on the Arduino board. There is a 7 second delay between switching the colour and this cycle should run continuously. When I press a button, I want the cycle to immediately switch back to green and continue the cycle (i.e. -> blue -> white -> red) again.

How should I go about this? Can you have a listener for a button press going at the same time as a delay? How do you interrupt the timer and change the active LED?

You could start with the attachInterrupt example sketch and work from there. Here is a possible solution:

enum { GREEN = 0, BLUE = 1, WHITE = 2, RED = 3};
const int buttonPin = 2;
const int ledPin[] = { 4, 5, 6, 7 };
volatile bool reset = false;
int state = GREEN;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  for (int i = 0; i < 4; i++) pinMode(ledPin[i], OUTPUT);
  attachInterrupt(digitalPinToInterrupt(buttonPin), doResetState, FALLING);
}

void loop() {
   digitalWrite(ledPin[state], HIGH);
   delay(7000);
   digitalWrite(ledPin[state], LOW);
   if (state == RED || reset) {
     state = GREEN;
     reset = false;
   }
   else {
     state = state + 1;
   }
}

void doResetState () {
    reset = true;
}

This will not immediately cycle back to GREEN when pressing the button but you can fix that by modifying the doResetState().

Cheers!