Atmega 328p at 3.3v : Internal vs external oscillator I am currently working on a pcb that uses smd atmega 328p (au).
I will be powering it through a lipo battery and a ldo regulator for 3.3v input. I am using the multiwii flight controller code.
I know that atmega runs at 8mhz at 3.3v and 16mhz at 5v without overclocking the chip.
The question is that should I use the internal 8mhz oscillator or external 8mhz?
I will definitely make the chip more accurate as given in some forums but still does this effects anything or not?

If the 8 MHz oscillator is off by a handful of percentage points, it will affect timing measurements you make using millis() and micros(). It could affect the baud-rates of Serial or SoftwareSerial. If these are not of any concern, the only remaining difference would be how fast your code can be executed. It's unlikely that the code pushes the chip runs so close to its maximum capability that it would matter, even at ~8 MHz.
Update:

... I just want to know if clock frequency effects the code and if I need
to change code a bit like for example blink sketch runs at different
time intervals on 8mhz and 16mhz(I tested it).

If you do nothing else, then yes, millis() will appear to run at half speed. You need to add a board definition to the IDE for an Arduino Uno running at 8 MHz. Then millis() and micros will be adjusted for the slower processor clock. How you do this depends on whether you choose the internal and less accurate 8 Mhz oscillator, or an external 16 MHz crystal.
For the internal oscillator, there is a board-definition on Github with instructions to load it into your IDE.
For an external oscillator, this article describes how to select the board type as "Arduino Pro or Pro Mini" and then be able to select the board frequency, using the Tools menu twice.


How to check my Arduino board is working or dead? When you have a board in your hand but you don't know is it working or not, how to verify if it's working or dead?

Note : After the @Ricardo's comment on my last post, I am posting this !

Plug the board into a USB port on your computer and check that the green LED power indicator on the board illuminates. Standard Arduino boards (Uno, Duemilanove, and Mega) have a green LED power indicator located near the reset switch.

An orange LED near the center of the board (labeled “Pin 13 LED” in the image below) should flash on and off when the board is powered up (boards come from the factory preloaded with software to flash the LED as a simple check that the board is working).

If the power LED does not illuminate when the board is connected to your computer, the board is probably not receiving power.

The flashing LED (connected to digital output pin 13) is being controlled by code running on the board (new boards are preloaded with the Blink example sketch). If the pin 13 LED is flashing, the sketch is running correctly, which means the chip on the board is working. If the green power LED is on but the pin 13 LED is not flashing, it could be that the factory code is not on the chip. If you are not using a standard board, it may not have a built-in LED on pin 13, so check the documentation for details of your board.

Online guides for getting started with Arduino are available at for Windows,  for Mac OS X, and for Linux.


Power Arduino Mega ESP85266 Is it possible to Power a Arduino Mega 2560 and a NodeMCU V2 ESP8266 ESP-12E from a single 9V Block?

What would be the best solution?

Can i power the ESP8266 directly via the Arduino Mega 5V output? (3.3V Output seems to weak)
Is a Power Converter like this for the ESP8266 necessary?
Should i use another external Power source for the ESP8266?

Thanks for any Help :)

Is it possible to Power a Arduino Mega 2560 and a NodeMCU V2 ESP8266 ESP-12E from a single 9V Block?

Yes. Assuming the "block" can provide enough current.

  Can i power the ESP8266 directly via the Arduino Mega 5V output? (3.3V Output seems to weak)

No.

  Is a Power Converter like this for the ESP8266 necessary?

Yes if you are powering it from more than 3.3V.

  Should I use another external Power source for the ESP8266?

Not necessary if the 9V one can provide enough current as I mentioned above.


Compilation error when trying to give pointer to a function to another function I'm trying to write a library for Arduino using the Wire library.
Here's my code:

PiCom.h:

#ifndef PiCom_h
#define PiCom_h

#include "Arduino.h"
#include <Wire.h>
class PiCom
{
public:
    PiCom(int address, int* integers[], double* doubles[]);
    static void onReceiveCallback(int numbytes);
    static void onRequestCallback();
private:
    //Actually arrays of pointers to the data to be sent, has to be declared that way cause the size of the array isn't known at compile time
    int** _integers;
    double** _doubles;

    void onReceive(int numbytes);
    void onRequest();

    static PiCom instance;
};

#endif

PiCom.cpp:

#include "Arduino.h"
#include "PiCom.h"

static void onReceiveCallback(int numbytes)
{

}

PiCom::PiCom(int address, int* integers[], double* doubles[])
{
    _integers = integers;
    _doubles = doubles;

    Wire.begin(address);
    void (*receiveFunction) (int);
    receiveFunction = &PiCom::onReceiveCallback;
    Wire.onReceive(receiveFunction);//Here i get an error
}

I want the  constructor to be created when a new instance is created. A mehtod in this object should be called when data is requested or received. When trying to pass onRequest(int) directly to Wire.onRequest(void (*) (int)) an error is thrown. Same happend when saving it to receiveFunction.

This problem was solved by using a static function (onReceiveCallback(int). I wanted this static function to call onRequest(int) in the object saved into PiCom::instance.

But now i'm getting another error:

PiCom\PiCom.cpp.o: In function `PiCom':
C:\Program Files\Arduino\libraries\PiCom/PiCom.cpp:26: undefined reference to `PiCom::onReceiveCallback(int)'
C:\Program Files\Arduino\libraries\PiCom/PiCom.cpp:26: undefined reference to `PiCom::onReceiveCallback(int)'

Pointer to a member function is a painful corner of C++ until C++11. This is why when you try to pass an instance method pointer to Wire.onReceive (without the static keyword), you will get an error similar to:

error: ISO C++ forbids taking the address of a bound member function to form a pointer to member function.  Say '&PiCom::onReceiveCallback'

Well, you can't argue with the C++ ISO standard... changing the function to a static one (with external linkage, as they say) is indeed a workaround, as you have found out.
For this workaround to compile properly you just need to omit the static keyword from your definition (where it is implemented), and leave your declaration (in the header file) as is:

PiCom.h:

...
static void onReceiveCallback(int numbytes);
...

PiCom.cpp:

void PiCom::onReceiveCallback(int numbytes)
{
    ...
}

By doing this you can pass it to Wire.onReceive without any problem, from the PiCom constructor, as follows:

PiCom::PiCom(int address, int* integers[], double* doubles[])
{
    ...
    Wire.onReceive(&PiCom::onReceiveCallback);
    ...
}


How can an Arduino determine the status of a washer or dryer using only vibration data? I'm trying to make an IoT washer/dryer device that will text me whenever my load is done. I was initially thinking to make assumptions about what data it should be receiving when the washer/dryer is running. However, I was wondering if there was a library that could analyze the data and "learn" what a cycle typically feels like. Should I:

a) keep it simple: when machine has been vibrating past a threshold for certain amount of time, consider it running. when it stops vibrating past time threshold, consider it done.

or

b) use some kind of learning algorithm to determine whether it has been stopped manually, an error has occurred, or it has successfully completed a cycle

Also, would option b be more practical on a device such as a Raspberry Pi?

I think the simplest option is to experiment first: record the vibration
level as a function of time during one wash cycle, and do that with a
few different washer models. Then look at your data and devise an
algorithm with your eyes on the measured curves. This is really the
only reasonable way to do any kind of signal processing: look at the
signal first. If you still have problems finding an algorithm, you can
come back here and show your data.

Unless you live in a region with huge geologic activity, chances are
that the vibration level of any washing machine will be well above the
background, which should allow you to choose a single vibration
threshold suitable for every model.


How to connect a 5V submersible motor to Node MCU? I connected the D1,D2 pins of the the Node MCU to the positive and negative of a 5V submersible motor. I wrote the following code, its getting uploaded without any errors but the motor is not working. I tested the condition of the motor by connecting to a battery,it does work.the code:

void setup() {
  // put your setup code here, to run once:
    pinMode(D1,OUTPUT);
pinMode(D2,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
digitalWrite(D1,HIGH);
digitalWrite(D2,HIGH);
}

I think you have got two issues here.

Firstly, as mentioned in the comments, you are driving the motor off the data pins so it will be getting less than 20mA which is almost certainly not enough to break the stall.  You need to use the digital pins to switch a MOSFET, transistor or relay (Electrical switch) and then that will switch on a larger supply directly from a "battery pack".  Have a Google for 'transistors' or 'relays' and see how they work, then you should get what I mean.

Secondly you seem to be using the pin names D1 and D2. There are a number of Node MCU boards out there but they all seem to have one thing in common and that is the pins labelled D1 and D2 on the board are generally not D1 and D2 in the code.

https://pradeepsinghblog.files.wordpress.com/2016/04/nodemcu_pins.png?w=924

If this is you board then unless you have a header file that does this for you, you should be using GPIO_5 and GPIO_4 for D1 and D2 (respectively).

Oh and the last thing, make sure you sub is leak proof :)


how to fix mirrored text on 3.2 inch IPS TFT LCD Display ILI9481 480X320 36 Pins for Arduino Mega2560 i am working on a project on my arduino mega2560. I want to show reading of the sensors on the TFT display, the problem is the text displayed on the screen is mirrored. Since i am very new to arduino i don't know how to fix the problem. I have check a few videos on youtube but nothing helped. I am using the example from the UTFT library arduino (AVR) => UTFT_DEMO_480x320

The orientation of the display is controlled by the "Set Address Mode" command (0x36) at line 42 of the ILI9481 driver.
The current value is 0x0A which is 00001010 in binary.  According to the datasheet (8.2.25) bit 6 is "Column Address Order", and that is set to "Left to Right" currently.
Turning that bit on should reverse the column order for the display.
So changing those two lines of code to:
LCD_Write_COM(0x36);
LCD_Write_DATA(0x4A);

should have the desired effect.


Output set to 'low' when new variable in buffer I would like to turn on and off the output of two pins on my arduino independently from each other. However, so far all my attempts have failed.

My current idea is to save the status (which I chose to be 0 as 'low' and 'high' as 1) of each of the pins in an integer array and then change the status of the pin depending of the entry in the variable. However, the entries in the variable are always set back to 0 and I do not know why this is happening.

This is my arduino code

const byte numChars = 32;
byte receivedChars[numChars];
boolean newData = false;
const int num_of_pins=2;
int output_pins[num_of_pins]={22,26};
int status_pins[num_of_pins]={0,0};

void setup() {
    int ii=0;
    Serial.begin(9600);
    for(ii=0; ii<num_of_pins; ii++){
        pinMode(output_pins[ii],OUTPUT);
    }

}

void loop() {
    recvWithStartEndMarkers();
    chooseFunction();
}

void chooseFunction(){
  if (receivedChars[0]==0){
    shutter();
    }
}

void shutter(){
        // get number of pin
        int pin_number_rcvd;
        int ii;
        int pin_status_rcvd;
        pin_number_rcvd=receivedChars[1];
        pin_status_rcvd=receivedChars[2];
        //check all status of pins and turn on and off
        for (ii=0; ii<num_of_pins; ii++){
          if (pin_number_rcvd==output_pins[ii]){
            status_pins[ii]=pin_status_rcvd;
          }
          if (status_pins[ii]==0){
            digitalWrite(output_pins[ii],LOW);
          }
          if (status_pins[ii]==1){
            digitalWrite(output_pins[ii],HIGH);
          }
        }
}

void recvWithStartEndMarkers() {
    static boolean recvInProgress = false;
    static byte ndx = 0;
    byte startMarker = 8;
    byte endMarker = 9;
    byte rc;

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (recvInProgress == true) {
            if (rc != endMarker) {
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }

        else if (rc == startMarker) {
            recvInProgress = true;
        }
    }
}

I use pyserial to send the input data to the arduino. my python code:

import serial
import time, struct, sys
ser=serial.Serial('COM17', 9600, timeout=10)
time.sleep(2)
ser.reset_input_buffer()
ser.reset_output_buffer()
pin_number= int(sys.argv[1])
high_or_low=int(sys.argv[2])

ser.write(struct.pack('>5B',8,1,pin_number,high_or_low,9))

I am using an ArduinoDue together with the arduino IDE.

Your problem is in one tricky option for arduino's com connection. When you reopen COM port where arduino is connected your arduino resets automatically.

Here's workaround from arduino.cc:

  DisablingAutoResetOnSerialConnection

  The simple way that doesn't require
  any permanent modifying of your hardware or software configuration
  changes:

  Stick a 120 ohm resistor in the headers between 5v and reset (you can
  find these on the isp connector too). 120 is hard to find so just
  combine resistors. Don't go below 110 ohms or above 124 ohms, and
  don't do this with an isp programmer attached. You can just pull out
  the resistor when you want auto-reset back.

http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection

Or you can just modify you script to be able to start over without reopening it.
For example use a loop there and some exit command to end that loop:

try:
    while True:
        do_something()
except KeyboardInterrupt:
    pass

https://stackoverflow.com/questions/13180941/how-to-kill-a-while-loop-with-a-keystroke
Replace do_something() with this part of your code:

ser.reset_input_buffer()
ser.reset_output_buffer()
pin_number= int(sys.argv[1])
high_or_low=int(sys.argv[2])

ser.write(struct.pack('>5B',8,1,pin_number,high_or_low,9))

I hope I was clear enough.


8X8 LED not lightning up according to matrix assignment on a Arduino Nano I'm currently trying to code a simple program that would allow me to light up an individual LED on an 8X8 LED board using a double array.

Here are the problems:

All the rows can ON individually UNTIL I turn all 8 rows ON. When I do this the last column turns OFF by itself (see attached pictures).

The columns aren't even working properly either. Every time I assign a column ON, the last column faintly turns ON too (one of the LEDs light in that column is broken so that is expect to be OFF. See picture).

I think those are the reasons why I am not able to singly assign a particular LED to be ON according to assignments in the array. If someone could spot my mistakes, it would greatly be appreciated. Thanks!

int led2 = 2;
int led3 = 3;
int led4 = 4;
int led5 = 5;
int led6 = 6;
int led7 = 7;
int led8 = 8;
int led9 = 9;
int led10 = 10;
int led11 = 11;
int led12 = 12;
int led13 = 13;
int led16 = 16;
int led17 = 17;
int led18 = 18;
int led19 = 19;

int rowPins [8] ={led19, led18, led11, led7, led12, led5, led4, led16};//assigning each LED to a row.
int columnPins [8] ={led13, led17, led9, led10, led2, led8, led3, led6};//assigning each LED to a column

int image [8][8]=
{

{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},

};

void setup()
{
  for (int i = 0; i<8; i++)
  {
      pinMode(rowPins[i], OUTPUT);
      pinMode(columnPins[i], OUTPUT);
  }
}//end of setup()

void loop ()
{
for (int y=0; y<8; y++)
{
 for (int x=0; x<8; x++)
 {
   if (image[x][y]==1)
   {
     digitalWrite (columnPins[x], HIGH);
   }
   else
   {
     digitalWrite(columnPins[x], LOW);
   }
 }//end of 2nd for loop

  digitalWrite(rowPins[y], LOW);
  delayMicroseconds(100);
  digitalWrite(rowPins[y], HIGH);
}//end of first for loop
}//end of loop

I don't see any program statements in the code as shown to cause the described behavior, and imagine it is some hardware problem.  (I'm assuming you put some non-zero values into the image[][] array; it looks to me like nothing should light up when image[][] is all-zeroes.)

Hardware problems break into several categories:  A wiring problem (which we can't see without much better pictures); incorrect software setup of HW; temporary misbehavior of the processor; or permanent damage.  For the sake of discussion, suppose temporary misbehavior applies.

Temporary misbehavior can be caused by overheating.  Overheating can be caused by drawing or sinking a lot of current for too long a time.  (If a large current is a fast transient event, it may have little effect.)

Note that most Arduino I/O lines are rated to sink or source at most 40 mA current each.  Ground and Vcc lines have higher limits, like 200 or 100 mA.  For more details see the spec sheet for your processor; also see ArduinoPinCurrentLimitations at arduino.cc, and Real maximum current for ATmega328? on Electronics SE.

If an LED is directly connected to 5V, it is likely to draw several times more current than nominal.  Connecting  an LED directly to an Arduino digital line also will allow it to draw too much current.  Connecting 8 LEDs to a single processor IO line is likely to cause enough overheating to damage the processor permanently.  You may need to add 8 or 16 resistors to your circuit.

Anyhow, instead of trying to debug while using a 100 μs multiplexing delay in your program, and instead of turning on lots of lights at the same time, try turning on one at a time for a brief but visible period each, and see if the array of lights scans ok, via code like the following:

int rowPins[]    = {19, 18, 11, 7, 12, 5, 4, 16}; //assign row lines
int columnPins[] = {13, 17, 9, 10,  2, 8, 3,  6}; //assign col lines

void setup() {
  int i;
  for (i=0; i<8; ++i) {
    pinMode(rowPins[i], OUTPUT);
    digitalWrite(rowPins[i], HIGH);
    pinMode(columnPins[i], OUTPUT);
    digitalWrite(columnPins[i], LOW);
  }
}
void loop () {
  int x, y;
  for (y=0; y<8; ++y) {
    digitalWrite(rowPins[y], LOW);
    for (x=0; x<8; ++x)  {
      digitalWrite (columnPins[x], HIGH);
      delay(250);     // wait about .25 seconds
      digitalWrite(columnPins[x], LOW);
    }
    digitalWrite(rowPins[y], HIGH);
  }
}

If multiple lights are on there may be miswiring on your project board, or the chip might be damaged, or there may be some roundabout leakage path from columns to ground or from rows to Vcc.  If you make the delay longer or add a pushbutton to advance manually, you can check voltages on LEDs and wires, or measure currents in wires, and perhaps deduce what the path is.


Wire over 1ft does not work with sensors SRF02 Im using an SRf02 ultrasonic sensor, and I need to make the wires long to elevate the sensor. They turn on and blink and are able to transmit a signal, yet they are not able to receive a signal. What is the error?

Using the internal pullup resistors for I2C is not recommended.  Arduino are very wrong in providing those as the default option and basically "hiding" the fact that I2C needs decent pullup resistors from you.

The internal pullup resistors, because they are so weak (i.e., a high resistance, typically > 50KΩ), do not pull the clock and data lines up adequately, and as such are only suitable for very short connections (in the order of a few inches).  Anything longer and the induced noise and inductance and capacitance of the wires will corrupt the I2C waveform.

I2C requires pullup resistors in the range of 2.2KΩ to 4.7KΩ.  As you can see that is more than 10x the pullup strength of the internal resistors.

For off-board connections (i.e., wires) you want the lower end of that range.  So add a 2.2KΩ resistor between SCL and +5V and another between SDA and +5V and you should find it works much better.


How does the PID controller actually work? Preferably PID functions on an Arduino uno or any other examples. I have been researching but many of the the websites really do not explain it.

P.S is there an algorithm for a PID? Thanks

How a PID controller works depends on the particular implementation.

There is a algorithm/library for PID on the Arduino: http://playground.arduino.cc/Code/PIDLibrary and an excellent explanation of the all of functions within it at http://brettbeauregard.com/blog/2011/04/improving-the-beginners-pid-introduction/

Over on stackoverflow and electronics, there are some good questions and explanations that might help:

https://electronics.stackexchange.com/questions/190606/understanding-a-pid-controller
https://stackoverflow.com/questions/14614124/how-do-i-use-a-pid-controller?rq=1
https://stackoverflow.com/questions/21516143/pid-control-value-of-process-parameter-based-on-pid-result?rq=1
https://stackoverflow.com/questions/13542447/i-dont-understand-integral-part-of-pid-controller?rq=1
https://stackoverflow.com/questions/21534996/pid-controller-intuition-for-when-error-0?rq=1


ESP8266: Interfacing MAX485 TTL-to-RS485 on serial port I am using the ESP8266 NODEMCU.
I am aware that the CH341 on the NodeMCU is bridged to the serial pins GPIO3(Rx) and GPIO1(Tx).
Hence, any data send on Rx and Tx is also visible on the serial monitor.
I need to interface MAX485 TTL-to-RS485 to the ESP8266 on different serial pins (other than GPIO3 and GPIO1).
Is there a way to configure other pins as Rx and Tx?
Please suggest any other ways to achieve this.
EDIT-1:
I need to use two serial ports at the same time (one with the CH341 and another with TTL-to-RS485). Please help with this.

You can't redefine pins on the ESP8266. You can, though, use SoftwareSerial to emulate a serial port. There's plenty of examples.
Also you need to use the MAX3485 on 3.3V devices. The MAX485 is for 5V devices.


How this smal infrared work I have a code that sends 384 pulses at 38kHz with an infrared LED. It's very easy to understand it. At the beggining the code sends the pulses using the LED and in the middle of the code I check the sensor if it has any signal coming. So far so good, yes? Please, take a look:

for(int i=0;i<384;i++) {
  digitalWrite(IRledPin,HIGH);
  delayMicroseconds(13);
  digitalWrite(IRledPin,LOW);
  delayMicroseconds(13);
}

if (digitalRead(IRsensorPin) == LOW){
  digitalWrite(D13ledPin,HIGH);
} else {
  digitalWrite(D13ledPin,LOW);
}

My question is this: I first send the pulses, so when I reach the line if (digitalRead(IRsensorPin) == LOW){ the pulse should already have passed the sensor. So why does it work? It should not work cause I first send the pulse and then I check for the pulse but as I understand the 384 pulses should already have passed the sensor.

I have no idea why this code works. I would be glad to listen smarter people to help me understand this.

Thank you.

The IR receiver does some filtering on the signal. It doesn't signal a LOW immediately if it lost a single pulse of light. A speck of dust, hanging in the air, might just be blocking the IR phototransitor. Or some brief flash of light, making two pulses seem like one or more.

These IR receivers a specifically build to filter out the 'noise' coming from other light sources and light obstructions.

Identically, you would want this receiver to give you a HIGH if it detect only 2 pulses of light 13uS apart. I could just be some sunlight reflected from a puddle, accidentally matching 38kHz.


Using more than one Ping Ultrasonic Range Finder I have done various applications with the Ultrasonic example project but it is always using one pinger. I'd like to make a scanner resting on a servo sweep but to reduce sweep time use more than one censor.

the documentation is rather basic ping sonic that states the signal 40khz is used.

Down to the question now. Is there a means to tell one pinger to use 40Khz and another say  45Khz.

This would allow me to scan two areas (different directions) per cycle, reducing the time frame to complete area scan by half.

There is no way to change the frequency, however there are other ways of doing what you want to accomplish. I think the best thing to do is stagger the timing of the pings so they don't happen at the same time.

Example code, modified by me:

#include <Servo.h>
Servo servo; // create servo object to control a servo

int pingPins[] = {7,8}; //The pins for the two sensors
char *pingString[] = {"Ping1", "Ping2"};

void setup()
{
  servo.attach(10); // attaches a servo to pin 10
  Serial.begin(9600);
}

void loop()
{
  unsigned long ultrasoundValue;
  for(int i = 0; i < ultraSoundSignalPins.length; i++)
  {
    ultrasoundValue = ping(i);
    Serial.print(pingString[i]);
    Serial.print(": ");
    Serial.print(ultrasoundValue);
    Serial.print("in, ");
    delay(50);
  }
  Serial.println();
  delay(50);
 }

//Ping function
unsigned long ping(int i)
{
  unsigned long echo;

  pinMode(pingPins[i], OUTPUT);         // Switch signalpin to output
  digitalWrite(pingPins[i], LOW);       // Send low pulse
  delayMicroseconds(2);                 // Wait for 2 microseconds
  digitalWrite(pingPins[i], HIGH);      // Send high pulse
  delayMicroseconds(5);                 // Wait for 5 microseconds
  digitalWrite(pingPins[i], LOW);       // Holdoff
  pinMode(pingPins[i], INPUT);          // Switch signalpin to input
  digitalWrite(pingPins[i], HIGH);      // Turn on pullup resistor
  echo = pulseIn(pingPins[i], HIGH);    //Listen for echo
  return (echo / 58.138) * .39;         //convert to CM then to inches
}

Sources:

https://stackoverflow.com/questions/20273971/arduino-multiple-ultrasonic-sensors-interference
http://forum.arduino.cc/index.php?topic=17898.0


Arduino IDE Serial Monitor - how to send NUMBERs - not charcters of numbers Serial link send and recieves Bytes. Serial monitor at Arduino IDE reads it's input as character.

So if I type '0' in serial monitor, then FW will read byte 48 - I don't want to implement some silly translation from character value to int - I want to input NUMBER as byte into serial monitor - how do I do that?

byte inByte = Serial.read(); // read the incoming byte
if(inByte == 1) // do stuff

I think the comments on your question are quite clear. The important point: any asynchronuous protocoll must include the info either how many bytes are transmitted or which byte is the last one. In "raw data", where each value (0-255) can be a legit data value, there is no way to use bytes for meta data. That's why typically only encoded data is transmitted: you have a small range of byte values that can contain the actual info (alphabet and digits) and you have a bunch of values that are free to be used as meta data. E.g. the commonly used \n as endbyte has the int value 10. How would you transmit the int value 10 in that case?

"I don't want to implement some silly translation from character value to int" - it's not silly, that's the way to go! What about float, boolean or negative values (8-bit, 16-bit, etc.)? You may even want to transmit structured data like python dictionaries. The only way the achieve this is using some kind of parser which knows the protocol.


Blank.txt at the End of Transmission I'm using my HC-05 (Master) to receive strings from a sensor (Slave), each string is suppose to have 7 items divided by ',' like so "a,b,c,d,e,f,g". I also have to write these strings in a .txt file in the SD card, being that I receive the strings and save them in a string array to later be written to a file. For some reason I can't receive it and write it to a file simultaneously, it alters the string. So the best way would be an array but when i open the file it's blank and when I print it on screen it starts correctly then prints only the first char of what would be the string. I tried it with 80 strings and it works correctly, so I can only guess it would be insufficient memory, But wouldn't it still write to the file since there is something in the strings.

PS:I'm using Arduino Mega

#include <SD.h>

const int tam=480;
char aux;
File myFile;

void setup() {
  Serial1.begin(115200);
  Serial.begin(115200);
  Capture();
}

void openSD()
{
  SD.begin(4);
  if( SD.exists("test.txt") )
  {
    Serial.println("O arquivo de amostras sera removido");
    SD.remove("test.txt");
      if( !SD.exists("test.txt") )
        Serial.println("Arquivo removido com sucesso!");
  }
  myFile = SD.open("test.txt", FILE_WRITE);
}

void Capture()
{
  String test[tam];
  openSD();
  Serial.println("BEGIN");
  for(int i=0;i<tam;i++)
  {
    test[i]="";
    do
    {
      while(!Serial1.available());
      aux=Serial1.read();
      test[i]+=aux;
      Serial.print(aux);
    }while(aux!='\n');
  }
  Serial.println("END");
  for(int i=0;i<tam;i++)
    myFile.print(test[i]);
  myFile.close();
}

void loop() {

}

Rules of sequential file is : It's saved when its closed, which mean if the file not closed properly, anything written before will not saved, and you'll get blank file.

so, if you get a blank file while you are sure that the data is received, the only possibility is your program doesn't reach

myFile.close();

one of the possibility is the received data not fit into your memory, so the '\n' is undetected.


Arduino classes, can't get property value I have tried hard to make a stepper motor work with a class, but I can't get a property returning its value in a method. I get 0 (zero) instead of 26 (expected) from _stepPin.

I have tried this->_stepPin with no success.

Here is the code. See the comments inside.

 class MKSStepperMotors {

   public:
    int _dirPin;
    int _stepPin;
    int _enablePin;

    MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

      int _dirPin = dirPin;
      int _stepPin = stepPin;
      int _enablePin = enablePin;

      //Habilitamos el motor
      pinMode(_enablePin, OUTPUT);
      digitalWrite(_enablePin, LOW);

      //Cambiamos la direccion y aumentamos la velocidad
      pinMode(_dirPin, OUTPUT);
      digitalWrite(_dirPin, LOW);

      // Le indicamos el pin de señal
      pinMode(_stepPin, OUTPUT);

    }

    void move(int steps, int stepDelay)
    {

      for (int x = 0; x < steps; x++) {
        Serial.println(_stepPin); //  <-- _stepPin is zero and not 26 as it should
        digitalWrite(_stepPin, HIGH); <-- _stepPin is zero and not 26 as it should
        delayMicroseconds(stepDelay);
        digitalWrite(_stepPin, LOW);  <-- _stepPin is zero and not 26 as it should
        delayMicroseconds(stepDelay);
      }
    }
};

 MKSStepperMotors pedo(28, 26, 24);

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

 void loop() {

      pedo.move(3200,100);

}

When you put the type there, you are creating new variables.  SO in your constructor:

 MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

      int _dirPin = dirPin;
      int _stepPin = stepPin;
      int _enablePin = enablePin;

You start by creating three new variables with the same names as the member variables defined in the class.  Throughout the rest of the constructor those get used instead of the ones that are member variables.

You gotta lose the "int" there.

You also have another bug in there.  The constructor may run before the init function if one of these objects gets declared at global scope.  Things like digitalWite and pinMode aren't going to work yet in that case.  A constructor should just have code to initialize variables, it should never touch hardware.  The stuff that uses hardware should be in another member function (usually called begin or init) that you can call from setup.


Not seeing frames returned from client when using ESP8266 Wifi Shield I'm trying to make a web server using an Arduino R3 and Sparkfun ESP8266 Wifi Shield. I've built a webpage that has a form I would like to control the Arduino with.

Currently my sketch can successfully send the webpage, but when I use the form, 9 / 10 times I see no output on the serial monitor, and the 1/10 times I see the frame from the client the sketch seems to hang and the client keeps waiting for more data.

I'm using the Sparkfun ESP8266 libraries for the product I bought.

I don't think this is a hardware problem, I've visually inspected the Arduino and ESP pins and they seem ok. I don't think it's a memory problem.

I've put the salient part of the sketch below:

void serverDemo()
{
  // available() is an ESP8266Server function which will
  // return an ESP8266Client object for printing and reading.
  // available() has one parameter -- a timeout value. This
  // is the number of milliseconds the function waits,
  // checking for a connection.
  ESP8266Client client = server.available(1000);
  char clientline[BUFSIZ];
  int index = 0;

  if (client)
  {
    Serial.println(F("Client Connected!"));
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;

    while (client.connected())
    {
      if (client.available())
      {
        char c = client.read();

        if( index < BUFSIZ ) {
          clientline[index++] = c;
        } // end of if

        if (c == '\n' && currentLineIsBlank)
        {
          clientPrintProgmemArray(htmlHeaderTable, htmlHeaderTableSize, client);
          clientPrintProgmemArray(webpageTable, webpageTableSize, client);
          Serial.println(F("Page sent"));
          break;
        } // end of if

        if (c == '\n')
        {
          currentLineIsBlank = true;
        } // end of if

        else if (c != '\r')
        {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        } // end of if
      } // end of if( client.available() )
    } // end of while ( client.connected() )
    delay(10);
    client.stop();
    Serial.println(F("Client disconnected"));
    Serial.print(F("Index: "));
    Serial.println(index);
    Serial.print(F("Clientline: \""));
    for( int i = 0; i <= index; i++)
    {
      Serial.print(clientline[i]);
    }
    Serial.print(F("\"\r\n"));
    if( strstr(clientline, "e=1") != 0) {
      Serial.println("hooray!");
    }
  }
}

The header and webpage the Arduino sends to the client is:

HTTP/1.1 200 OK
Content-Type: text/html
Connection: close
<!DOCTYPE HTML>
<html>
<body>
<form action="/?" method="get">
    <input name="e" type="submit" value="0">
    <input name="e" type="submit" value="1">
</form>
</body>
</html>

The output I get on the serial monitor is:

ESP8266 Shield Present
Mode set to station
Connected to: XXXXX
My IP: 192.168.0.13
Server started! Go to 192.168.0.13

Client Connected!
Page sent
Client disconnected
Index: 2
Clientline: "
 "
Client Connected!
Page sent
Client disconnected
Index: 2
Clientline: "
 "

I'd be very grateful if anybody has any advice on where the problem lies.

Thanks in advance

So I figured out the answer to my own question.

It turns out there must be a mistake in the example sketches that come with the ESP8266 shield I bought, as the function to begin Arduino/ESP8266 communications didn't have any arguments when the function expected parameters. So it appeared to be trying to set their baud rate to 0!!

I edited the library to have a hard value of 57600 and now it seems to work far more reliably.


Programmed 5 Volt output to power a relay I need to put out 5 volts from an Arduino UNO digital pin. I've read that the pins can do approx. 5 volts, but I need to know if it will actually reach 5. I'm also powering a few other devices from the Arduino.

Are the digital pins capable of emitting 5 volts consistently? Are there any better alternatives?
Thanks.

Your concern for the output capability of the pin should be its current sourcing or sinking capability, not its voltage. Arduino pins typically have a limit of 40ma per pin and a total maximum of 200ma. This is for the Atmega328p (you didn't say which Arduino you're using. You'll need to drive motors or relays or anything else with a substantial current requirement with a driver circuit powered independently of the Arduino itself. That can be with a shield made for the purpose or a circuit you design and build into your project. Motors and relays in particular need snubber diodes to protect the driving circuits from inductive "kickback" or spikes generated in their coils.


Tracking one Nrf24l01 by another I am working on an Asset locator using Arduino and nrf24l01. I want one of the nrf24l01 to track another which is attached to an object. How can it be done?

You have to divide this project in separate steps:

Use a GPS to get the coordinates
Send the GPS coordinates via the nRF24L01 to the 'controller'

Possible limitations:

GPS only works outside; otherwise use gyro/compass etc as addition
Range limitations
Power limitations

If you don't want to use GPS, you might be able to use 2 nRF24L01s which send a signal at exactly the same time, track it with a third one (attached to the object), calculate the difference in times and based on that calculate the distance to both other nRF's and calculate the position. You might even need a third sender.

Of course this is quite tricky, like synchronization of time between messages and the need for multiple nRF's, also at different distances/directions to be reliable.


Connect 2 LSM9DS0 to Flora So I'd like to connect two of these sensors to an Adafruit Flora (https://www.adafruit.com/products/2020). In the product page it says you can only connect one but in the forum an admin said that you could do it but it required a bit of hacking. I'm new to arduinos and circuits in general. Can someone tell me how I could do this, or at least point me in the right direction?

Edit

I decided to use this multiplexer to use LSM9DS0's with the Flora.
https://www.adafruit.com/products/2717

Adafruit's rectangular 9DOF device, unlike their round 9DOF, brings several more signals out to pads.  When using I²C with the rectangular 9DOF board, as I understand it signal pin SA0_G can be set low or high to modify the device address:

  The SDO/SA0 pins (SDO_XM/SA0_XM or SDO_G/SA0_G) can be used to modify the least significant bit of the device address. If the SA0 pin is connected to the voltage supply, LSb is 1 (ex. address 0011101b) else if SA0 pad is connected to ground, the LSb value is 0 (ex. address 0011110b).

Controlling that signal should let you put multiple 9DOF's on one system.  (See my answer to  question 13830 for some additional comments on setting an I²C address.) Also see tables 15 and 16 on page 33 in the spec sheet (DM00087365.pdf) regarding addresses.

If you insist on using round 9DOFs for this application, you would need to find the trace from pin 22¤ of the LSM9DS0 to Vcc on one of your 9DOF boards; working under a microscope with miniature tools, cut the trace and rewire the pin end of the trace to Ground.  This will change that board from using addresses 0x1D and 0x6B to 0x1E and 0x6C, if I correctly understand the spec sheet.

It probably would be a good idea to get one of the rectangular 9DOF's so that you could experiment with changing its addresses, before modifying one of the round ones.

¤ Looking at the top of the chip, pin 24 is just clockwise from the depressed round dot marking pin 1; pin 22 is 1.75 mm from the corner.  See Figure 21, LGA 4x4x1 mm 24-lead outline, in the spec sheet.  That figure shows the underside of the chip.


Why is this extremely simple code not working? I have a problem with a for loop, and Serial.print("Its Working") does not appear. Seems simple, I've done it before, now for whatever reason, its not working anymore
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

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

  for (int x = 0; x > 10; x++) {

    Serial.println("Its Working");
    delay(1000);
  }
}

The problem is:
for (int x = 0; x > 10; x++) {

That can be rewritten, in pseudo code, as:

X is zero
While X is greater than 10:

Increment X

You see the problem? X is zero. It's not greater than 10, so it never increments.
I assume you actually wanted:
for (int x = 0; x < 10; x++) {

Also be aware that your for loop will be run over and over again, so you will never see it finish.  You should add
Serial.println("Loop done");

at the end so you know it's finished.


writing and uploading sketch as cpp file I want to use only *.cpp files and no *.ino anymore. I read a lot of stuff about how to upload c++ instead of arduino sketches. But still I was not able to find a step by step guide how to do it.

Actually I am developing my sketch within Spacemacs (Emacs) and uploading it with Arduino-Makefile (https://github.com/sudar/Arduino-Makefile)

When I now want to start a new project with only *.cpp and *.h files to use classes etc. how would I start? Does anybody has the time to describe a rough step-by-step without the trivial stuff?

See my post about How the IDE organizes things.

Also see my page about how to avoid the quirks of the IDE sketch file pre-preprocessing.

You can certainly manage without .ino files. As Edgar Bonet says, they are really C++ files with certain pre-processing (see link above).

  but what about these loop() and setup() functions

Effectively, the Arduino IDE supplies a main function that looks like this:

int main ()
  {
  init ();    // initialize hardware, including timers and timer interrupts
  setup ();   // user setup
  while (true)
    loop ();  // stuff to be done repeatedly
  return 0;   // this will never be executed
  }

(It's slightly more complex, to allow for USB where applicable, but that is the idea).

  But still I did not found the step by step guide how to do it.

I'm pretty sure there are a lot of example "make" files around which show the idea.

I have an example here.


Bluetooth module(HC05) works with Arduino Uno but not with breadboard (ATmega328) I am currently working on a project that requires communication between an android phone(galaxy s4) and an ATmega328 microprocessor. To connect these devices wirelessly I'm using an HC05 bluetooth module and to understand the connection I'm using pre-built arduino codes(turn LEDs on and off) and an android app called blueterm.

This connection is established and able to transmit data when connected to the Arduino uno, but as soon as this chip is removed and connected to a standalone breadboard the connection fails. The standalone breadboard works fine and has been tested with many other projects and I have attached the breadboard connection below. The HC05 when connected to the breadboard changes the blinking pattern to notify the user it is connected but the serial connection is never made. Any help would be greatly appreciated, if any other information is needed feel free to ask.

If the LED is blinking, the device is waiting to pair with another Bluetooth transceiver (your phone). Once paired, the LED will stay lit. The factory-set pairing code is usually 1234. I can't tell from the photograph how the HC-05 Rx & Tx are wired to your ATmega328, but note that it must be cross-connected; that is Rx -> Tx and Tx -> Rx.


Connecting a FireBeetle ESP32 to Arduino I have a very basic question, because I struggle to upload files to my FireBeetle ESP32 Board.

When I try to upload to the board I get an

A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header

On other boards you have to press & hold the flash button, but this specific board just has a reset button.
What can I do?

The flash button is virtual and controlled by the RTS signal from the computer through the USB port (why are you trying to connect through an Arduino?). It should automatically enter bootloader mode when you go to program it. There should be nothing you need to do.

However, if you do want to manually enter bootloader mode, just connect IO0 (note: not D0) to GND and press the reset button.


How do you make an Arduino count down timer? I want to make a countdown timer with a LilyPad Arduino for 3 seconds with red (1 second), then orange(1 second), then yellow (1 second), then green (3 seconds), all being triggered by a button. I want to check to see if I have the right code. I am a self taught programmer, so apologies if this is a little messy. (or a lot)

#include <Adafruit_NeoPixel.h>
const int inputPin = 3;

void setup() {
  // put your setup code here, to run once:
  pinMode(inputPin, INPUT_PULLUP);
  strip.begin();
  strip.show();
}

void loop() {
  // put your main code here, to run repeatedly:
  If (digitalRead (inputPin) == LOW) {
    For (int i = 0; i < 12; I++) {
      Int pixelNum1 = 1;
      strip.setPixelColor( pixelNum1, 244, 0, 0);
      strip.show();
      delay (27);
      pixelNum1 ++;
    }

    For (int i = 0; i < 24; I++) {
      Int pixelNum2 = 1;
      strip.setPixelColor( pixelNum, 247, 247, 0)
      strip.show();
      delay (27);
      pixelNum ++;
    }

    For (int i = 0; i < 12; I++) {
      Int pixelNum3 = 1;
      strip.setPixelColor( pixelNum, 0, 247, 41)
      strip.show();
      delay (27);
      pixelNum ++;
    }
  }
}

For (int i = 0; i < 12; I++) {
      Int pixelNum1 = 1;
      strip.setPixelColor( pixelNum1, 244, 0, 0);
      strip.show();
      delay (27);
      pixelNum1 ++;
    }

Assuming you fix the upper-case lower-case issues here first, you've still got a scope issue.  Since pixelNum1 is defined inside the for loop, it will go out of scope at the end of the for loop.  So it will be 1 on every iteration and it won't increment like you seem to think it will.

Why don't you just get rid of it altogether and use i+1 instead?


Infrared sending not working slight misconfiguration? Edit: Took some advice from below but it still doesn't work. I think it probably blocking code but please tell me how I could fix it to send a the valid infrared signal, NOTE: I wouldn't actually code it like this I am just trying to learn and understand how to do it and then make it better after:
uint8_t Status;
uint8_t Counter;
const uint32_t Code[] = {4507,4507,573,1694,573,1694,573,1694,573,573,573,573,573,573,573,573,573,573,573,1694,573,1694,573,1694,573,573,573,573,573,573,573,573,573,573,573,573,573,1694,573,573,573,573,573,573,573,573,573,573,573,573,573,1694,573,573,573,1694,573,1694,573,1694,573,1694,573,1694,573,1694,573,46560};

void setup() {
  pinMode(4, OUTPUT);
}

void loop() {
  while(Counter<70) {
    if (Status=1) {
        digitalWrite(4, HIGH);
        Status=3;
        while(Status=3) {
          delayMicroseconds(26);
          digitalWrite(4, HIGH);
          delayMicroseconds(26);
          digitalWrite(4, LOW);
        }
        delayMicroseconds(Code[Counter]);
        Status=2;
        Counter++;
    } else {
      if (Status=2) {
        digitalWrite(4, LOW);
        Status=0;
        while(Status=0) {
          delayMicroseconds(26);
          digitalWrite(4, HIGH);
          delayMicroseconds(26);
          digitalWrite(4, LOW);
        }
        delayMicroseconds(Code[Counter]);
        Status=1;
        Counter++;
      }
    }
  }
}

There are two basic things wrong here - one with your understanding of the timings, and the other with your understanding of how IR communication works.
First the timings - those are both ON and OFF timings. You don't just turn on for a defined length of time - you turn on for a defined length of time and then turn off for another defined length of time.
So for the timings in your code 4507,4507,573,1694,573,...etc... you would:

Turn on
Wait 4507us
Turn off
Wait 4507us
Turn on
Wait 573us
Turn off
Wait 1694us
Turn on
Wait 573us
... etc ...

You have no "off" time in your code, only ever on times.
Secondly is your understanding of IR communications. It does not involve turning an LED on or off for defined times. It's not as simple as that. Instead you are controlling the modulation of an LED.  When the LED of an IR remote control is "on" it's not just turned on - it's rapidly turning on and off. The receiver looks for the presence or absence of this rapid turning on and off light. This is the "carrier frequency" of the signal and must match what the receiver is looking for.
Typically this is between 30kHz and 50kHz depending on the receiver.
So you need some way of generating that rapid on-off signal. Normally this is done using PWM by the IR libraries and switching between 0% and 50% duty cycle for the off and on periods of the signal you want to send.
So it's far simpler to just use a library that does all this underlying work for you.


Extracting char array out of function I have a array called Table1 witch contains '1','2','3','4'
I do not want to work with global variables
I want to change the content of Table1 with a function called 'Change' that gives a return char array back in to Table1

This is the program i wrote:

void setup()

{
  Serial.begin(9600);
}

void loop()
{
  char tabel1[4] = {'1','2','3','4'};
  int i;
  for (i = 0; i <= 3; i++)
  {
    Serial.println(tabel1[i]);
  }

  tabel1 = Change(tabel1);

  for (i = 0; i <= 3; i++)
  {
    Serial.println(tabel1[i]);
  }
}

char Change(char tabel2)

{
  tabel2[0] = 'n';
  tabel2[1] = 'b';
  return tabel2;

}

This is the error i'm getting:

In function 'void loop()':
testArray:17: error: incompatible types in assignment of 'char' to 'char [4]'
tabel1=Change(tabel1);
^
In function 'char Change(char*)':
30:12: warning: invalid conversion from 'char*' to 'char' [-fpermissive]
return tabel2;
^
exit status 1

[Error] Exit with code=1

You should read something about C arrays and how they work.

Anyway, if you use:

  Change(tabel1);

// ...

void Change(char * tabel)
{
  tabel[0] = 'n';
  tabel[1] = 'b';
}

It'll change passed array because it's passed as pointer to the first element of tabel1.


Integrating Freescale Multi Sensor board with Arduino I recently bought Freescale's FRDM-FXS-MULTI-B, and have been trying to integrate it with an Arduino UNO. The board descriptions say that it has the shield layout that matches that of an Arduino shield. So in theory, I should be able to integrate it fine.

The problem comes when I plug it in and try to program the Arduino. As soon as I plug it in, the board resets and hangs. If I try to upload a simple code (just reading the analogue signal from the light sensor), the IDE hangs when uploading. Sometimes, I can fix it by removing the shield and pressing the reset button, but sometimes that doesn't work: the computer doesn't recognise the Arduino on the port, and the IDE removes the port from the Port Selection option. When I do remove it and it resumes functioning normally, and I re-attach the shield, the board resets and hangs again, until I go into the Serial Monitor.

With this board, I realised the Bluetooth module is connected to the Serial Receive pin, which explains the hang in the IDE, but I cannot understand why it resets and hangs when I plug it in.

Does anyone have any experience with this board, and can help me out? Why can I not find any tutorials online? With the multitude of sensors on this shield, I'm guessing you can access them via normal I2C and SPI communications, right? How do you use the Bluetooth module on the board?

So... 20 months later I stumbled upon this question, only to find out I wrote it. Awkward! Anyway, for anyone who stumbles across this question in the future, here is the answer.

The Rx pin is connected to the Bluetooth module, and as such the module will keep the pin in an idle state (either idle-high or idle-low). The Rx pin of the Arduino UNO (or the Rx0 pin on the Mega/Due) requires to be free of anything that may interfere with the upload. The Arduinos rely on the Rx pin for the sketch upload. If anything is connected to it, the IDE will freeze and nothing will be uploaded. Simply disconnect the FRDM board, upload the code, and put the board back in place. Then it should work.


utility/spi_com.h error when compiling Marlin for Arduino mega with Ramps 1.4 I am using win 8.1 and trying to load Marlin 2.0.x onto Arduino Mega with an attached Ramps 1.4 board fitted with 3 8825 Drivers. Unfortunately everytime I try to compile It concludes with the following error. Can anyone please help.
Alternatives for utility/spi_com.h:
[]ResolveLibrary(utility/spi_com.h)  -> candidates: []In file included from C:\Users\Dad\AppData\Local\Temp\arduino_build_750275\sketch\src\HAL\STM32\MarlinSPI.cpp:23:0:C:\Users\Dad\AppData\Local\Temp\arduino_build_750275\sketch\src\HAL\STM32\MarlinSPI.h:28:12: fatal error: utility/spi_com.h:
No such file or directory   #include <utility/spi_com.h>

compilation terminated.
Using library SPI at version 1.0 in folder: C:\Users\Dad\Downloads\arduino-1.8.13-windows\arduino-1.8.13\hardware\arduino\avr\libraries\SPI
exit status 1
Error compiling for board Arduino Mega or Mega 2560.

trying to load Marlin 2.0.x onto Arduino Mega

I have no specific knowledge of Marlin.
For the moment, I'm ignoring the fact that it seems to be looking for STM32 files which would seem to play no role on an Arduino Mega.
I cloned the Marlin github repo and found no mention of a file "MarlinSPI.h" in the 2.0.x branch.  There is however a MarlinSPI.h in tag 1.1.9.1
You appear to be working with the code for the wrong version (or branch) of Marlin.


Arduino Force sensitive Resistor with an lcd So we were asked to do something with a force sensitive resistor so naturally i thought of a project which takes the name of the main component which is force and applies it ,mine works by as  you apply more and more pressure to the sensor it takes this value and displays it on an lcd but the display should be a bar graph which increases as the pressure increases. the problem is i dont really know how to do a bar graph on a 16x2 lcd. Please help. (my lcd has an I2c)

here is my code for the pressure sensor so far

int fsrAnalogPin = 0; // FSR is connected to analog 0
int fsrReading;      // the analog reading from the FSR resistor divider

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

void loop(void) {
  fsrReading = analogRead(fsrAnalogPin);
  Serial.print("Analog reading = ");
  Serial.println(fsrReading);
  delay(100);
}

ok so i improved my code and i finally got it this code displays the force detected by the fsr into a bar graph

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <LcdBarGraphX.h>
#include<LcdBarGraph.h>

byte lcdNumCols = 20; // -- number of columns in the LCD

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);   // -- creating LCD instance

int fsrAnalogPin = 0; // FSR is connected to A0

// -- creating a 4 chars wide bars
LcdBarGraphX lbg0(&lcd, 16, 0, 0); // -- First line at column 0 and row 0 with 16 columns

void setup(void) {
  Serial.begin(9600);   // We'll send debugging information via the Serial monitor
  lcd.begin(4, lcdNumCols); // start lcd with 2 rows and 16 columns
  lcd.clear();
  delay(100);
}

void loop(void) {
  lbg0.drawValue( analogRead(fsrAnalogPin), 9); // the 9  is the maximum range you want for pressure
  Serial.print("Analog reading = ");
  Serial.println(fsrReading);
  delay(100);
}

From the Library Manager, install the LcdBarGraphX library by Balazs Kelemen.

There are several examples there as well.


Arduino TimerOne breaks the program when calling "digitalRead" I'm trying to make this project.

But i have a problem running this code. It appears to be val = digitalRead(inPin); breaks entire program. just because i call this from the callback function which attached as an interrupt function Timer1.attachInterrupt(callback);

Here is the more simplified problem simulation program,

#include "TimerOne.h"

int inPin = 7;   // sensing digital pin 7

int val;

void setup() {
  pinMode(inPin, INPUT);      // sets the digital pin 7 as input to sense receiver input signal

  Serial.begin(9600);
  Timer1.initialize(8);  // initialize timer1, and set the frequency; this drives both the LC tank as well as the pulse timing clock
  // note: modify this as needed to achieve resonance and good match with the desired tags
  // the argument value is in microseconds per RF cycle, so 8us will yield RF of 125kHz, 7us --> 143kHz, etc.

  Timer1.pwm(9, 512);

  Timer1.attachInterrupt(callback);
}

void callback()
{
  val = digitalRead(inPin);//once you comment this line, it works fine
}

void loop() {
  Serial.print("Program running \n");

}

Any help is much appreciated.

The time between 2 interrupt triggers is only 8us. Also digitalRead() is a quite big function, that needs some time to execute (I don't know how much). That way it is to short for the Serial print command to execute in the leftover time. Make the following change and you will see, that it works.

void loop(){
  noInterrupts();
  Serial.print("Program running \n");
  interrupts();
  delay(1000);
}

Now the interrupts are disabled during the execution of the Serial.print(), so that it can finish. After this the interrupts are enabled again and we wait for 1 second to give the interrupts some time before we are disabling them again.

The speed of the Arduino is limited, so you cannot do much, when constantly triggering interrupts in the pace of 8us. If you only want to check this digital input you can get the value directly with using the PINB registers (refer to this side), which works much faster.

Also you should consider making the variable val volatile, since it will can change everytime through your interrupt service routine.


Arduino Servo is behaving strangely I am trying to use the Arduino Servo library to drive a simple servo and am having some difficulty getting it to even move.

Here's the setup:

And the schematic that Fritzing generated for me:

And the code:

#include <Servo.h>

int SERVO_SIGNAL_PIN = 9;

Servo servo;
int pos = 0;
bool GOING_UP = true;

void setup() {
    // Attach the servo and give it a few seconds to reset to the starting position.
    servo.attach(SERVO_SIGNAL_PIN);
    servo.write(0);
    delay(5000);
}

void loop() {
    if((GOING_UP && pos < 180) || pos == 0) {
        GOING_UP = true;
    } else {
        GOING_UP = false;
    }

    int step = 1;

    if(!GOING_UP) {
        step *= -1;
    }

    pos += step;

    servo.write(pos);
    delay(15);
}

When I run this, nothing happens. When I attach a multimeter and set it to the "6V" setting, I have found some strange readings:

When I connect the red multimeter lead ("red lead") to the 5V line connecting the Arduino to the breadboard, and the black multimeter lead ("black lead") to the black GND line connecting the Arduino to the breadboard, I get readings around 5V; but...
When I connect the red lead to the red power line going to the servo, and the black lead to the black GND line coming back from the servo, I get a voltage reading of roughly -20V!!!

I'm not sure what this means/implies. Is anything jumping out at anyone? Anything I can troubleshoot here? Thanks in advance!

The odd voltages might suggest that the servo isn't actually (fully) connected to the Arduino. As it's a diagram of the breadboard layout, not a photo, I can't say for sure, but on some breadboards the +ve/red and -ve/black rows are sometimes split in the middle. i.e. if you were to connect the Arduino's +5v to one end of the breadboards red row, and the servo to the other end, they might not be joined (same applies for -ve/black). Just a thought; apologises in advance if I’m stating the obvious.


433Mhz receiver only get values of 0, 1, 2 I have two Arduino Uno and a few sets of transmitters and receivers. I followed some guide on the internet to make them work and that's what I did so far but I still get random values of 0 or 1 or 2, no matter what signals I am trasmitting.

I connected the receiver's VCC to 5v on Arduino; the receiver's data to A0 on the Arduino; the receiver's GND to the Arduino's GND.

I connected the transmitter's VCC to 5v on Arduino; the transmitter's data to  on Arduino; the transmitter's GND to the Arduino's GND.

This is the transmitter code:

#define dataout 12
#define ledPin 13
unsigned int temp = 0;

void setup() {
  pinMode(dataout, OUTPUT);
  pinMode(ledPin, OUTPUT);
}

void loop() {

  digitalWrite(dataout, HIGH);
  digitalWrite(ledPin, HIGH);
  delay(5000);
  digitalWrite(dataout,LOW);
  digitalWrite(ledPin, LOW);
  delay(5000);
}

This is the recriver code:

const int datain=A0;
#define ledPin 13

int temp = 0;
const unsigned int upperThreshold = 500;
const unsigned int lowerThreshold = 100;

void setup() {
  pinMode(datain, INPUT);
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  temp=analogRead(datain);
  Serial.println(temp);
  delay(300);
  if(temp<lowerThreshold) {
    digitalWrite(ledPin, HIGH);
  }

  if(temp>upperThreshold) {
    digitalWrite(ledPin, LOW);
  }
}

I tried to change the transmitter and receivers. I tried to change Arduino boards. I tried to change analog to digital, nothing worked...

Suggestions?

Update:

Here are some pictures of my gear:

This is the output of the receiver when both Arduinos work near each other, there no sync between the signals transmitting and receiving.

  0 1 0 0 0 0 1 1 0 2 1 2 1 0 1 362 0 1 1 1 1 1 0 2 0 314 2 2 1 0 0 2 1
  0 1 2 1 1 2 0 1 1 0 1 1 2 1 0 0 0 0 2 1 0 1 0 0 1 0 1 0 1 1 1 2 2 1 1
  2 1 1 1 1 1 0 211 2 0 2 0 0 1 2 0 0 759 1 2 1 1 2 1 2 0 1 16 0 0 1 1 0
  0 2 1 1 0 1 2 1 2 0 2 1 0 2 0 1 2 1 1 2 2 1 2 0 0 1 0 1 1 2

This is the output when I tried to disconnect the GND and VCC from the receiver:

  433 426 431 422 379 367 362 394 405 412 406 394 399 388 356 258 193
  438 507 507 499 486 478 473 449 442 431 428 427 424 425 423 422 419
  417 414 413 413 409 410

Those cheap 433 MHz RF modules require a (good) library to work. The VirtualWire/RadioHead library is the best.

The VirtualWire library it outdated, but still used.

The RadioHead library has a few bugs fixed, but uses more memory.
Use it in RH_ASK mode, see the included 'ask' examples.

[Update: better quality]
Most cheap 433 MHz ASK transmitters work with 3.5 to 12V. They have the longest range at 12V. About 20 meters is no problem with 5V, but if longer range is needed then transmitters that are only made for 5V are better.
The cheap 433 MHz receivers use a coil to tune the frequency. They are very sensitive and they do work well. However, when such a module is placed near metal or close to the Arduino, the frequency might change. Modules that use a crystal for the frequency are better. Sometimes a sensitivity is mentioned (for example -112dBm) but I don't know how reliable that is. When an antenna of 16 cm does not work well, try an antenna of more than a meter.

The transceivers are better for wireless data transfer, but that depends on the use.
Sparkfun has Wireless Buying Guide.
RadioHead has a list of supported transceivers.

The nRF24L01+ are very cheap. I read that every one of them on Ebay or Aliexpress is counterfeit, but the counterfeit chips do work. They work at 3.3V, and are 5V tolerant.

The CC1101, CC2500 and so on are good, but not often used with an Arduino. The same for Si4432, Si4436 and so on. If you know a good library, they are very good transceiver chips.

Adafruit is using the RFM69 a lot. For example the Feather Packet Radio board.

Last but not least: don't forget Wifi and Bluetooth.


Does 'digitalPinToInterrupt' work with analog pins I have an interrupt signal attached to the A12 pin of an Arduino Mega 2560.

Would the following source line activate the interrupt processing?  I am calling the digitalPinToInterrupt function on an Analog pin.  It compiles fine.

attachInterrupt(digitalPinToInterrupt(A12), MessageFromIOBInt, FALLING);

where my interrupt code is

void MessageFromIOBInt(void) {
    ++gNumInterrupts;
}

Interrupts only work on interrupt pins. Trying to translate a pin number into an interrupt number for a pin that isn't an interrupt pin will never work.

  External Interrupts: 2 (interrupt 0), 3 (interrupt 1), 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2). These pins can be configured to trigger an interrupt on a low level, a rising or falling edge, or a change in level.

Many pins (including the analog pins) can use the pin change interrupt. This requires an external library which has its own way of interfacing with them (see the examples).


Error: `nullptr` was not declared in this scope. Arduino IDE I try to use this ArduinoThread library. In the Arduino I go Sketch->Import Library->ArduinoThread. After that I have the following line in the beginning of the sketch:
#include <ThreadController.h>
#include <Thread.h>
#include <StaticThreadController.h>

I leave setup() and loop() empty and try to verify or upload the sketch on my Arduino board. But I get the following errors:

Is this about the library or I do something wrong?

I installed Arduino IDE in two different ways (only god knows why). The first one was via using of manager apt-get and other was manually via downloading, unzipping and installation through the install.sh file.
It seems that on Ubuntu 14.04 the

sudo apt-get install arduino

command provides an installation of an old version of Arduino IDE.
So eventually I was launching Arduino IDE by arduino command in my terminal (actually I was using d-menu in i3). No surprise it ran the old one installed by apt-get. I just removed that version by

sudo apt-get remove arduino

And now I am using executable arduino inside unzipped folder. Actually, I am not using Arduino IDE explicitly at all. I am using a Makefile from here.


Need Help to Select Microcontroller ?? Help i am doing a project which has to run in side a garage to control water levels in sump pit as well as in overhead tank . also schedule running of  pumps.

i have to run 5 pumps  (two for ground water to sump pit , three for sump pit to  over head tank) check two levels also need to check when pump goes on the water is flowing or not if not try another pump

the micro controller should last at least two years .

the temperature inside garage where micro controller board will be kept will go to 47 centigrade in summer to 15 centigrade in winter .

i see many options :

1.arduino uno

2.arduino uno from sparfu and adafruit

3.Sparkfun Arduino Fio

4.SparkFun Arduino Pro Mini 328

5.Adafruit Metro Mini 328

6.Adafruit METRO 328

7.Particle Photon

what whould i use ?

We cannot say, what single board you need to use. There are many boards, that are fitting to your requirements. You yourself have to choose.

Most of your listed boards use the same microcontroller (as Juraj wrote in his comment):
The Arduino Uno (doesn't matter where you buy it, it's the same) and all the boards with a 328 at the end use the Atmega238P. The Sparkfun Arduino Fio uses an Atmega32U4, which is different from the 328P, but not a very big jump (though it implements native USB support). These are all AVR based microcontrollers. The Particle Photon is not an Arduino. It uses an ARM processor and has wifi.

To choose from the big amount of boards on the market, you should look into your requirements:
- How many outputs do I need? Only simple digital outputs or also PWM? If the latter, how many individual PWM pins do I need?
- How many inputs do I need? Only digital or also analog?
- What extra devices do I need? Relays for motors/high loads? Special boards? And how do they need to be connected (what interfaces they use)?
- What interfaces do I need to the outside world? LCD Display + Buttons? Bluetooth? Wifi? Or nothing?
- How computationtime- and memory-consuming are the calculation tasks, that I need to perform (resources)?
- What environment will the project be in?

Based on the answers, you can choose a board, that fit's all the requirements and still leaves a bit headroom for further development. To help you I will write some examples for your project, that might be fitting for you.

Outputs: I guess your pumps are using mains power or similar (Be VERY carefully with mains power. It can easily kill you!). You need a relay to control these. It would be easiest to use a complete relay board, that includes all the needed extra circuitry. Then you just need to use one digital output pin per controlled pump, which results in 5 pins needed.
Inputs: This depends on what level sensors you have. If they have a digital signal (like a simple switch, that triggers, when it is covered by water), you just need to tie one digital input pin to each level sensor. With 2 level sensors per tank and 2 tanks we need 4 digital input pins for level sensing.

If the level sensors work with an analog voltage, you need to use 4 analog input pins. Their usage is a bit different, since their voltage has to be converted to a number value by the ADC (Analog Digital Converter) inside the microcontroller.
Interfaces: This is mostly up to you, since you didn't specify anything. You can just build the device with any outside interfaces, if you don't need them. Then you also can use a board without wifi. If you think, that adding wifi in the future would be a great idea, you can use a wifi capable board and just disabling wifi, until you need it. (Thinking a bit in the future, what future development might get interesting for this project)
Resources: Controlling motors (pumps are only motors for the microcontroller) based on some simple inputs is somewhat the standard task for a simple microcontroller. It doesn't need much computation power, neither much memory.
Environment: The temperature is not a problem for you. Basically all microcontrollers can operate in temperatures up to 80°C und down to -35°C (the exact values can be found in the datasheet of the corresponding microcontroller). The humidity is more of a problem. You need to build a water resistant casing for the electronics of your project, so that no water can get on the electronic parts. Also - to be sure - you should put one or two of these little silica bags into the casing, which sometimes come with electronic devices or such. The silica bags will bind the water in the air inside the casing and will keep the electronics even more dry.

So you need a simple microcontroller with 5 digital outputs and 4 inputs (digital or analog depending on your sensors), so in total 9 free fitting pins. An Uno or some of it's variants are fitting for this. If you want it smaller, that the Uno, you might want to use the Nano, which is the same as the Uno, just smaller. If you want wifi capabilities, you can go with an ESP variant like the NodeMCU.

This is just an example. There are many ways to build such a project, so there is no definitive answer. Any microcontroller, that fit's your requirements, is ok for the job.


detecting presence inside - PIR or ultrasound? (I am professionally a software guy working in the GCC compiler with MELT, so I am fluent in software, but much less in hardware - I did use a solder for a 74LS00 nand gate based stuff in the 1990s. This is my first Arduino project)

My first Arduino project would be to automate the lights and the fan in my inhouse WC toilet in Paris (France) suburb. I bought several Arduino Nano v3 boards. I'm thinking of driving with a relay a low voltage 12v LED lightbubble. I want to detect human presence in the toilets. I'm thinking of some PIR sensor, but I am afraid that PIR won't detect anything if the temperature is above 37°C (or about 100F), which is unusual in Paris (France) but may happen a few days per year (I've got no air conditioning). Is my worry correct, or can a PIR still work with very warm outside temperature? Should I use an ultrasound detector instead?

PIR sensors work fine and are probably easier to program for than ultrasonic sensors. For example, this tutorial on a PIR sensor sold by Adafruit has a datasheet at the bottom that says:

Operating Conditions Operating Temperature -20 ˚C to +70 ˚C
Storage Temperature -30 ˚C to +80 ˚C
Operating Voltage 3 to 10 V at Rs = 47 kΩ

You can try to find and check the datasheet for the sensor you intend to purchase to determine if it will work.


Arduino Asynchronous Function Crash I'm trying to make two functions one will be running in a loop the second one will be running with a time interval of 1 seconde
I made a piece of code to do so it runs fine in the beginning but after a bit of time (aproximately 35 secondes) the code loses its mind and starts executing without caring about the delays.
I don't know what's going on
here is my code

void loop() {
  if(millis()-prev>=gap){
    Serial.print("Prev: ");Serial.println(millis()-prev);
    prev = millis();
  }

  Serial.print("Prev2: ");Serial.println(millis()-prev2);
  delay(mils);
  prev2 = millis();
}

You can try it yourself the code runs fine at the begining but bugs after some time.
What i'm trying to acomplish is having some code that runs in a loop and a function that will run each seconde.
the code is tried on multiple boards of Arduino Uno.

Your problem is that you use delay() in your loop. This stops the code execution for the given time, so no wonder your code starts to frickle after some time.

To achieve what you want try this:

void loop() {
  if(millis() - prev >= gap){
    Serial.print("Prev: ");Serial.println(millis()-prev);
    prev = millis();
  }
  if(millis() - prev2 >= mils){
  Serial.print("Prev2: ");Serial.println(millis()-prev2);
  prev2 = millis();
 }
}

EDIT If you try to create a frequency generator, it won't work that way - read this thread and look at the program in the last third which uses bitbanging technique to achieve that. Here an example of a wave generator (with extra hardware)


Digispark ATtiny85 keyboard I have a small project that I have in mind and I'm pretty new with Arduino.

I want to make a small device that if a key was pressed it would do something.

Now I know I could use a button with the device but I want to specifically use a Cherry MX Blue Switch.

So I wanted to know if the test code I wrote up would get me in the right stating place and I want to know where I would wire the key switch onto the board.

From how I have the code written I'm guessing I connect the positive pin from the switch to P0 on the board and the other pin to ground on the board, is this correct?

#include "DigiKeyboard.h"

void setup() {
    pinMode(0, INPUT);
}

void loop() {
    // put your main code here, to run repeatedly:
    if(digitalRead(0)==HIGH){
        DigiKeyboard.sendKeyStroke(MOD_GUI_LEFT,KEY_R);
        DigiKeyboard.print("test");
    }
}

I would suggest to connect one pin of the with to 5v and the other to ground. The Arduino will be able to detect 5v as logic HIGH.

The code looks correct except for better programming technique I would suggest to indent you code, this make debugging easier for longer programs:

#include "DigiKeyboard.h"

void setup() {

   pinMode(0, INPUT);

}

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

  if(digitalRead(0)==HIGH){

    DigiKeyboard.sendKeyStroke(MOD_GUI_LEFT,KEY_R);
    DigiKeyboard.print("test");

  }
}


Arduino on breadboard, and then soldered using a board made on Eagle but won't work So I'm looking to create an arduino clone to mount on one of my robots. I started off making the arduino on a breadboard, using the instructions found on Arduino's own website and I succeeded. It works as well, I've checked it with the "blink" project.

I then drew the schematic in Eagle:

Next, I created a board and routed it, giving the following result:

Finally, I transferred it onto a copper clad, soldered it, but it doesn't work. Tried pretty much everything I could think of but there seems to be something wrong and I cant work out what it is.

Can someone please help?

Hassan

I haven't worked out why it's "not working", but some comments on your PCB:

Your crystal is too far from the clock pins
Your crystal capacitors are most definitely too far from the crystal
There are no decoupling capacitors on your Vcc / AVcc pins

Your crystal should be right next to the pins on the chip that it is connected to, and the capacitors for it should be immediately next to that. The layout you have at the moment, if it actually works, will be radiating huge amounts of EMI and would immediately fail any emissions test you'd care to perform.

Without decoupling capacitors on the power pins the chip may not function properly.

Edit: I have just found your main mistake

You haven't linked the output of your regulator sub-circuit to Vcc. Power gets regulated but goes nowhere.


ATtiny85 soft-latching, and sensor-waking: Are multiple switches differentiable by pin change interrupt? I am using a vibration switch with a pin change interrupt on an ATTiny85 to wake the processor and run some code when the vibration switch grounds an input pin. The circuit is battery-powered, so sleep mode is important. I would now like to add another input switch (momentary pushbutton) between an internal pullup on the ATtiny and ground to use as a soft latching switch to accomplish on/mode/off (power-on/case-selection/power-off). I'd like the vibration-wake-sleep code to be one of the cases selectable by the pushbutton. The ATtiny85 has one hardware interrupt (pin2 aka INT0), and the rest are pin change interrupts available on the other I/O pins.
After reading around, my understanding is that the pin change interrupts cannot be separated to run pin-specific code, as they all trigger the same pin change interrupt effect. Is that correct?
To put it another way, do I need to put my pushbutton on the hardware interrupt pin, or can I put it on any old I/O pin and still be able to use the vibration switch on another I/O pin only when I select that mode, without it triggering the same effect as the pushbutton every time there's a vibration? Or is there a better way? I'm trying to minimize the number of components, as this is a space-constrained project. Thanks!

If you have one dedicated interrupt signal, and enable the shared pin change interupt for only one pin, then you have no ambiguity - the hardware ISR is caused by the dedicated pin, and the shared pin change ISR is caused by the only enabled pin change pin.

Where things get more complicated is if you enable more than one pin to trigger the pin-change interrupt.  In this case, either the ISR or whatever follows in cause from it will need to figure out which pin caused the interrupt.

Unless I'm overlooking it in the data sheet, the ATtiny pin change interrupts don't have a register which latches the causing condition, so you may have to look at the actual pin input register.   The catch is that things like contact bounce might make the causing signal no longer present at the exact instant you check it.  However, contact bounce is typically a more serious problem when releasing a contact than closing it.

Some things you can do:

In the ISR, don't actually do anything, but set an "interrupt happened" flag.  Then in the main program, poll the inputs for a while until you see one actually asserted, and act on that.  You should only need to stay awake for a small fraction of a second before you catch the responsible contacts closed when you are looking.
You could try to use a small capacitor to slow the rate at which the pullup resistor responds to the switch bouncing back open, in the hopes of  making sure that the causing condition is seen when the ISR itself looks.

In either case you will probably want to stay awake and keep the pin change interrupt disabled until the switch has been released, and for maybe a hundred milliseconds thereafter to let release bounces die out.  Then you can re-enable the interrupt and go back to sleep.

Do keep in mind that regardless if the MCU is awake or not, if someone wedges the product into packing material or something which holds the switch closed in opposition to the pullup resistor, then that pullup resistor itself may drain your battery over a few weeks/months.


I bought USB > FT232RL, can I use it to program a bootloader onto an Arduino? I bought this thing off of eBay:

eBay Link

Will it allow me to program an ATmega[xxx] (Arduino clone) with a bootloader?
 --> If so, how would I go about it? What should I do, and what should I certainly not do?
 --> If not, what do I need (or where can I learn) to be able to use an Arduino clone with the Arduino IDE?

I'm a bit new to Arduino, and since I learned that a fair amount of the clones being sold on eBay don't have a bootloader, I wondered how to fix this. (and the "barebones" seem to be quite a bit cheaper)

Answer - summarized from different answers below (as I can only mark one answer below as accepted):

Can you use an FT232R to burn a bootloader onto an AVR (such as an ATmega328)?

=> Yes you can, though it's a bit annoying to do, as it's slow and a bit more complicated than just plug and play. See the first part of Chris Stratton's answer below.

I already have a working Arduino style board, can I use that?

=> Yes, you can use for example a UNO-style board to program another. This process is explained here: http://arduino.cc/en/Tutorial/ArduinoISP, which was referenced in the second part of Chris Strattons' answer below.

The two options above are too much of a hassle for me, or I don't have an Arduino yet/available, is there another option?

=> Yes, you can buy a USB to ISP (In-System Programmer) board/programmer. They're pretty cheap and are called USBISP or USBASP for example. Here's an example: http://www.ebay.com/itm/180980285082, referenced at the end of MatsK's answer. (or an even cheaper one: http://www.ebay.com/itm/390806886235).

In fact, you can, but you are unlikely to enjoy it as it will be fairly slow.

While this module is intended for serial communications - which the ATmega won't support until it has a bootloader on it - the chip around which it is built can also be operated in "bitbang" mode:

http://www.ftdichip.com/Support/Documents/AppNotes/AN_232R-01_Bit_Bang_Mode_Available_For_FT232R_and_Ft245R.pdf

Using reconfigured pins of this wired to the ISP pins of your target, and an implementation of the ISP algorithm running on the PC, it will indeed be possible to load a bootloader on to a new ATmega chip.  However, USB is not designed for this type of usage - it is meant to move large blocks of data, rather than to efficiently do sequences of tiny operations.  The result is that the loading process will be drastically slower than with other methods.  You may also spend a fair amount of time tracking down software to do it, or writing your own.

If you have an already working Arduino-style board available, you can use that to program your new chip:

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


Read Multiple Sensors Data from a text file located in SD Card in Arduino/ESP32 I am working on a small home project 'glucose meter' via non invasive techniques. I am using four sensors like RGB color sensor, two multi-wavelength photo diodes (A & B) and temperature sensor (K-Type Thermocouple). I am using Multi Regression algorithm to estimate Glucose level in human body by calculate all four readings from sensors.

I am using ESP32 and I am saving all my sensors data in a CSV file (or text) after taking more than 20 calibration data from my family and friends. I can read this file after writing but I am facing a problem in reading all calibration data from this text/CSV file in the following particular manner.

Y,Sensor1,Sensor2,Sensor3,Sensor4
92,103,25,65,9875
91,104,26,62,9805
105,92,30,66,9600
150,60,40,75,9233
...,...,...,.....

Above pattern indicates 'Y' values (Blood Sugar value mg/dl) and corresponding sensors value on that time.
I am facing problem in reading these object like:

Y1 = 92, S1 = 103, S2 = 25, S3 = 65, S4 = 9875
Y2 = 91, S1 = 104, S2 = 26, S3 = 62, S4 = 9805
....................AND so forth..............
Y1000 = XX, S1 = XX, S2 = XX, S3 = XX, S4 = XX

Can any one help me how would I read and categorize each sensor values from the text/CSV File?

Thanks.

Function file.parseInt(), will skip non numeric characters and then parse the number stopping on non numering character. So you need only call file.parseInt() for every value in row, process the data and then loop to next row.

Y1 = file.parseInt();
S1 = file.parseInt();
S2 = file.parseInt();
S3 = file.parseInt();
S4 = file.parseInt();


Arduino + ESP8266 as Webserver I want to connect Arduino to my Home Wifi and make it serve as a server to access GPIO pins on Arduino from remote (like controlling LED connected to Arduino from remote).
I am using ESP8266 to connect to my wifi network.
I am facing some issues like:

sometimes it doesn't connect to my wifi router.
not connecting to my mobile Hotspot.
not able to serve default and AP mode.

I am following tutorial from http://allaboutee.com/2014/12/30/esp8266-and-arduino-webserver/
Here is my code:

#include <SoftwareSerial.h>
#define DEBUG true

SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(115200); // your esp's baud rate might be different

  sendData("AT+RST\r\n",2000,DEBUG); // reset module
//  sendData("AT",2000,DEBUG); // send AT command
//  sendData("AT+GMR\r\n",2000,DEBUG); // returns firmware
//  Serial.println("checking mode");
//  sendData("AT+CWMODE=?\r\n",5000,DEBUG); // check supported modes
//
//  Serial.println("scanning APs");
//  sendData("AT+CWLAP\r\n",21000,DEBUG); // scan list of access points

  Serial.println("set mode 1");
  sendData("AT+CWMODE=1\r\n",5000,DEBUG); // configure as both mode

//  Serial.println("joining AP");
  sendData("AT+CWJAP=\"<MY_WIFI_SSID>\",\"<WIFI_PASSWORD>\"\r\n", 16000, DEBUG); // connect to wifi

  Serial.println("Testing CIFSR");
  sendData("AT+CIFSR\r\n",7000,DEBUG); // get ip address

  Serial.println("setting for multiple connection");
  sendData("AT+CIPMUX=1",2000,DEBUG); // configure for multiple connections

  Serial.println("print MAC address");
  sendData("AT+CIPSTAMAC?\r\n",2000,DEBUG); // print current MAC address

  Serial.println("set port 80 for server");
  sendData("AT+CIPSERVER=1\r\n,80",2000,DEBUG); // turn on server on port 80
}

void loop()
{
  if(esp8266.available()) // check if the esp is sending a message
  {

    if(esp8266.find("+IPD,"))
    {
     delay(2000);

     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     String webpage = "
Tyagi IoT
<button>LED1</button>";

     String cipSend = "AT+CIPSEND=";
     cipSend += connectionId;
     cipSend += ",";
     cipSend +=webpage.length();
     cipSend +="\r\n";

     sendData(cipSend,1000,DEBUG);
     sendData(webpage,1000,DEBUG);

     webpage="<button>LED2</button>";

     cipSend = "AT+CIPSEND=";
     cipSend += connectionId;
     cipSend += ",";
     cipSend +=webpage.length();
     cipSend +="\r\n";

     sendData(cipSend,1000,DEBUG);
     sendData(webpage,1000,DEBUG);

     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId; // append connection id
     closeCommand+="\r\n";

     sendData(closeCommand,3000,DEBUG);
    }
  }
}

void sendData(String command, const int timeout, boolean debug)
{
    esp8266.print(command); // send the read character to the esp8266
    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {
        // The esp has data so display its output to the serial window
        Serial.write(esp8266.read());
      }
    }
}

Are you using an arduino (as in UNO / mini / nano etc.) and communicating with a separate esp8266 via serial?
I've found esp8266 module to be more reliable by using a 12e or such like and running arduino boot loader on it. There's more memory to play with, and I tend to formulate the data I need within the ESP8266 and then communicate with that via serial or I2C to get data / requests to and from.

Make sure you're supplying the ESP module with enough current - they're juicy little things, so good 300mA @3.3v and use a good 470uf 10v cap or something too.. They can splurge current on occasion, particularly when scanning networks.

Let me know what set up you're running

Cheers


Playing Melody with Tone() without using delay() Is there a method to play a Melody with Tone() without using the delay() function?

tone(8, melody[thisNote], noteDuration);
int pauseBetweenNotes = noteDuration;
**delay(pauseBetweenNotes);**

As others have noted, this can be done using the same method as used in the standard 'BlinkWithoutDelay' example sketch, and combining that with a state-machine type approach. In a simple state machine you'd assume you can be in one of two states: outputting a tone, and not outputting a tone.

Applying these ideas to your code snippet above:

// BEFORE SETUP
const int tonePin = 8;
unsigned long previousMillis = 0;
const long interval = pauseBetweenNotes;
const long interval = noteDuration;
boolean outputTone = false;                // Records current state

// IN LOOP
unsigned long currentMillis = millis();

if (outputTone) {
// We are currently outputting a tone
// Check if it's been long enough and turn off if so
    if (currentMillis - previousMillis >= noteDuration) {
        previousMillis = currentMillis;
        noTone(tonePin);
        outputTone = false;
    }
} else {
// We are currently in a pause
// Check if it's been long enough and turn on if so
    if (currentMillis - previousMillis >= pauseBetweenNotes) {
        previousMillis = currentMillis;
        tone(tonePin, melody[thisNote]);
        outputTone = true;
    }
}


Is it possible to connect miband2 and arduino nano (?) I want to make an IOT project using an Arduino nano and I need heart rate sensors. I I have a miband2. So, is it possible to connect them ?

You need to connect as a central device.
I've had good luck with the adafruit nrf52 feather.  Also see: https://github.com/Freeyourgadget/Gadgetbridge for the protocol.


Help with LCD's menu and seeing values continuously I want to see the voltage data using void volt();, when I go to the "Item2SubItem3" within void menuChanged. Now I can only see the data at that time: how can I refresh the value every second?

void setup()
{
    // setup()...
}

void loop()
{
    //loop()...
}

// DC Voltometer
float vPow = 4.7;
float r1 = 100000;
float r2 = 10000;

void volt()
{
    lcd.clear();
    float v = (analogRead(0) * vPow) / 1024.0;
    float v2 = v / (r2 / (r1 + r2));
    lcd.setCursor(0, 0);
    lcd.print("DC VOLTOMETER");
    lcd.setCursor(0, 1);
    lcd.print(v2);
    delay(1000);
}

void menuChanged(MenuChangeEvent changed)
{
    MenuItem newMenuItem = changed.to; // get the destination menu
    lcd.setCursor(0, 1);            // set start position for lcd
                                 // printing to the second row

    if (newMenuItem.getName() == menu.getRoot())
    {
        lcd.print("Main Menu       ");
    }
    else if (newMenuItem.getName() == "Item1")
    {
        lcd.print("Item1           ");
    }
    else if (newMenuItem.getName() == "Item1SubItem1")
    {
        lcd.print("Item1SubItem1");
    }
    else if (newMenuItem.getName() == "Item1SubItem2")
    {
        lcd.print("Item1SubItem2   ");
    }
    else if (newMenuItem.getName() == "Item2")
    {
        lcd.print("Item2           ");
    }
    else if (newMenuItem.getName() == "Item2SubItem1")
    {
        lcd.print("Item2SubItem1   ");
    }
    else if (newMenuItem.getName() == "Item2SubItem2")
    {
        lcd.print("Item2SubItem2   ");
    }
    else if (newMenuItem.getName() == "Item2SubItem3")
    {
        lcd.print("Item2SubItem3   ");
        delay(2000);
        volt();
    }
    else if (newMenuItem.getName() == "Item3")
    {
        lcd.print("Item3           ");
    }
    else if (newMenuItem.getName() == "Item4")
    {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Item4           ");
    }
}

As Gerben implied in a comment, menuChangeEvent is called only when the menu selection changes.  Thus, your voltmeter readout will print only whenever you change the menu selection to Item2SubItem3.  The code shown below illustrates how to modify your loop() so that it checks the menu selection once per second.  Each second the main loop will do whatever function is currently selected, such as displaying a current voltmeter reading.  Note, you can make the menu decoding shorter and less tedious as shown in the answer, and can put variable declarations near where they are used instead of in random places.

void setup() {
}  // setup()...

// DC voltmeter reading
void volt () {
  const float vPow = 4.7, r1 = 100000, r2 = 10000;
  lcd.clear();
  float v = (analogRead(0) * vPow) / 1024.0;
  float v2 = v / (r2 / (r1 + r2));
  lcd.setCursor (0,0);
  lcd.print("DC Voltmeter");
  lcd.setCursor (0,1);
  lcd.print (v2);
  // Don't delay(1000) since loop() takes care of delay.
}

long int second = 0;
uint8_t itemcode = 0; // Will be number nm for Item n, Subitem m
int passnumber = 0;
void menuChanged(MenuChangeEvent changed) {
  MenuItem menuitem = changed.to; //get the destination menu
  String itemname = menuitem.getName();
  lcd.clear();        // Make printing spaces at line ends unnecessary
  lcd.setCursor(0,1);         //set lcd printing position = second row
  if(newMenuItem.getName() == menu.getRoot()){
    lcd.print("Main Menu");
    itemcode = 0;
  } else {
    lcd.print(itemname);
    itemcode = 10*(itemname[4] & 7);
    if (itemname.length() > 5)
      itemcode += itemname[itemname.length()-1] & 7;
  }
  passnumber = 0; // Actions can test passnumber if they like
  second = 0; // Cause actions to take place now
}

void loop() {
  long int now = millis()/1000; // Get elapsed-seconds
  if (now == second) return;    // Only do stuff once per second
  // Update to current second and do chosen menu item
  second = now;
  switch (itemcode) {
  case  0: break;
  case 10: break;
  case 11: break; // Fill in with code for different cases
  case 12: break;
  case 20: break;
  case 21: break;
  case 22: break;
  case 23:    // Item 2, subitem 3, read voltmeter
    volt();
    break;
  case 30: break;
  case 40: break;
  }
  // You can test passnumber to control for cases that only go once
  ++passnumber;
} // end of loop()

Edit: I moved the declaration of second and added second = 0 within menuChanged() to decrease latency between a menu item being selected and its action taking place.  Without second being zeroed in menuChanged(), up to a second could pass between an item's selection and its action; latency would average 0.5 seconds, which is undesirable in a user interface.


How do i fill the second byte? I am using I2C communications to control a AD5694RBRUZ (http://www.analog.com/media/en/technical-documentation/data-sheets/AD5696R_5695R_5694R.pdf) with my Arduino Nano. If i enter two bytes it wil Wire.write only the first line from top to bottom. In the datasheet it is shown that you muust first fill the command byte, then the high and last the low byte. How can i fill the low byte? I have now scraped the idea to input two bytes separately and decided to input one uint16_t byte. How do i fill the low byte at the same time as the high byte, or if it possible how to input the uint16_t value?

My code is as follows:

#include <Wire.h>

#define Address 0x0D

void setup()
{
Serial.begin(9600);
Wire.begin();
AddressWrite(0x3F,0x05B0);
Serial.print ("Biti = ");
Serial.println (AddressRead(0x01));
}

void loop()
{
}

void AddressWrite (byte Naslov, uint16_t Cifra1)
{
byte Hi, Lo;
Hi = highByte(Cifra1);
Lo = lowByte(Cifra1);
Wire.beginTransmission(Address);
Wire.write(Naslov);
Wire.write(Cifra1);
Wire.endTransmission();
Serial.print ("Biti Hi = ");
Serial.println (Hi);
Serial.print ("Biti Lo = ");
Serial.println (Lo);
Serial.print ("Biti Cifra = ");
Serial.println (Cifra1);
}

byte AddressRead (byte naslov)
{
Wire.beginTransmission(Address);
Wire.write(naslov);

Wire.requestFrom(Address,2);

while(!Wire.available())
  {
  }

return Wire.read();
}

Thank you for your time and help.

You can use a number of Wire.write to write data.
The AD5694R should get three bytes and two bytes can be read from it. There is a "multiple dac readback sequence", but that is an extra.

Your AddressWrite requires an extra Wire.write.
Your AddressRead is missing a Wire.endTransmission and the while(!Wire.available()) should be removed.

void AddressWrite (byte Naslov, uint16_t Cifra1)
{
  byte Hi, Lo;
  Hi = highByte(Cifra1);
  Lo = lowByte(Cifra1);

  Wire.beginTransmission(Address);
  Wire.write(Naslov);       // command byte
  Wire.write(Hi);           // msb first
  Wire.write(Lo);           // lsb second
  Wire.endTransmission();
}

uint16_t AddressRead (byte naslov)
{
  Wire.beginTransmission(Address);
  Wire.write(naslov);       // command byte
  Wire.endTransmission(false);  // repeated start

  uint16_t hi, lo, result;
  Wire.requestFrom(Address,2);
  hi = Wire.read();
  lo = Wire.read();
  result = word(hi,lo);
  return result;
}

I have added a repeated start, because that is according to the datasheet.

Could you make the names more according to the datasheet ? For example 'command' or 'commandByte' instead of 'Naslow'. And perhaps better names for the functions, for example 'writeAD5694R' instead of 'AddressWrite'.


Can I remove soldered atmega328P from arduino board, using hot air gun, without damaging it? I need to remove atmega328P from arduino board and the best tool what comes up to my mind is a hot air gun. What is the maximum temperature that atmega328P can withstand?

web search reveals the peak reflow temperature is 260°C

the chip will withstand that for 15 seconds or so

here is an example graph of a reflow oven temperature during the reflow process