Set PWM by period? And have it variable? In this other stack QA I'm asking about generating a pulse signal with a period ranging from 63 ms to 6.5 ms. There is a popular PWM library however it doesn't compile and also since 63 ms is 15.8 Hz, that library's integer Hz setting isn't of help.

Is there a definitive process that isn't waving incense bundles in the corners of the room? There is an over abundance of "how tos" on the internet, however, none seemed to get me to a solution.

I've got a Mega and am using TIMER5. It's "just like" TIMER1 in that it is a 16 bit timer.

I stumbled upon a solution via trial and error coupled with watching the results on an o'scope.

The best guidance came from a Stack Exchange QA. Setup isn't particularly special, however the combination of WGM bits here worked and I didn't investigate further. Of the biggest importance are the prescaler divider bits, the least three significant bits of TCCRxB. 001 means no dividing or prescaling of the clock.

It all boiled down to 4 registers and the pinMode() call. Ultimately, seven lines of code:

#define PULSE_PIN 45
void setup() {
    // IMPORTANT: Clear Timer/Counter Control Registers
    TCCR5A = 0;
    TCCR5B = 0;

    // Set Timer/Counter Control Registers
    TCCR5A = B00101001; // Phase and frequency correct PWM change at OCRA
    TCCR5B = B00010010; // least sig bits sets "carrier frequency" by dividing CPU clock
    //  Observation:
    //  TCCR5B = B00010010 and OCR5A = 16667 results in period of 16.70 mSec
    //  meaning OCR5A is period in uSec when TCCR5B = B00010010
    //  TCCR5B = B00010001 : OCR5A = 20000 results in period = 2.5 mSec 399.3Hz

    pinMode(PULSE_PIN, OUTPUT);
}

In the sketch, I watch an analog pin with a potentiometer on it and map its sweep to an effective RPM range of 950 to 9000 RPM. Hence the arbitrary range of periods I want to handle. When loop() sees the ADC change, the below code adjusts the PWM accordingly.

Note that no floating point data types are used. The magic numbers below were chosen by trial and error in a spreadsheet with values rounded to whole numbers.

void setRpm(){
    //  Getting to period in uSec from rpm the long way to keep
    //  the answer in range of the data type:
    unsigned int rpm = map(pot_adc, 0, 1023, RPM_MIN, RPM_MAX);
    unsigned long period = rpm/50;
    period = 24000/period;
    period = period*50;
    //  The trigger lasts 26°, so the PW is 26/360 * period.
    dwell = period/36;
    dwell = dwell*26;
    dwell = dwell/10;

    //  OCR5A is a counter the carrier frequency counts up to,
    //  which sets output period / frequency
    //  meaning OCR5A is period in uSec when TCCR5B = B00010010
    OCR5A = period; //  OCR5A is period in uSec when TCCR5B = B00010010
    //  OCR5B is the width of the pulse. If we used floats,
    //  we could use duty cycle * period.
    OCR5B = dwell;
}

Obviously, this code will have limitations to the range of frequencies it can handle, but the Internet has plenty of means for higher frequency PWM, especially when the desired PWM is fixed and doesn't need varying.

The most helpful way to see the control registers is as binary positions and not to rely upon macros, masks, and bit shifting. This comment block helped greatly:

 // WGM modes:
 // TCCR1A
 // Bit              7      6      5      4      3     2     1     0
 // Bit Name         COM1A1 COM1A0 COM1B1 COM1B0 ----- ----- WGM11 WGM10
 // Initial Value    0      0      0      0      0     0     0     0
 // changed to       1      1      1      1      0     0     0     1

 // TCCR1B
 // Bit            7      6      5       4        3        2        1        0
 // Bit Name       ICNC1  ICES1  -----   WGM13    WGM12    CS12     CS11     CS10
 // Initial Value  0      0      0       0        0        0        0        0
 // changed to     0      0      0       0        1        0        0        1
 // CS12,CS11,CS10 = (0,1,1) = prescaler divide by 64


Can I use an Arduino Uno to support an RFID reader, Zigbee module and a touch screen at the same time? I'm almost a beginner to microcontrollers and have done a few simple projects, but this time I have to use an Arduino Uno (powered by a battery) to support an RFID reader (RC522), a Zigbee module and a touch screen altogether. Apparently there are too few pins to support all the modules. What is the easiest way to implement such a system?

Also I don't know what the RFID, zigbee and touch screen uses (generic GPIO pins, I2C, SPI, something else)?

You always can combine multiple inputs/outputs using a multiplexer (i.e. 74HC165, 74HC595), although it will mean extra software and less performance.

About the touch screen, that might be problematic regarding performance and memory usage, since the Uno has only a few KB and even the more expensive Arduino's do not have that much memory you might need.


Make system with ultrasonic sensor and servo I want to create a system where the servo will make the ultrasonic sensor move and detect the area in front of it. I have made the program but when run the ultrasonic sensor can not detect as usual.

Does anyone have another program or why my program is not running as planned?

This is the source code :

#include <Servo.h>

const int trigPin = 10;
const int echoPin = 9;
int lampu = 13 ;

// membuat nama objek servo untuk pengontrolan servo
Servo myservo;
// variable untuk menyimpan posisi servo
int pos = 0;
long duration, inches, cm;
void setup() {
  Serial.begin(9600);
  pinMode(lampu, OUTPUT);
  myservo.attach(7);
}

void loop() {
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
  inches = microsecondsKeInchi(duration);
  cm = microsecondsKeCenti(duration);
  Serial.print(inches);
  Serial.print(" in, ");
  Serial.print(cm);
  Serial.print(" cm");
  Serial.println();

  lampuNyala() ;
  servo();
  delay(10);
}

// start dari 0 derajar sampai 180 derajat
long microsecondsKeInchi(long microseconds)
{
  return microseconds / 74 / 2;
}

long microsecondsKeCenti(long microseconds)
{
  return microseconds / 29 / 2;
}

void servo(){
  for(pos = 0; pos < 180; pos += 1)
  {
    // pada posisi 1 derajat
    // memberitahu servo untuk pergi ke posisi  'pos'
    myservo.write(pos);
    // tunggu 15ms untuk pencapaian  posisi servo
    delay(30);
  }
  // start dari 180 derajat ke 0 derajat
  for(pos = 180; pos>=1; pos-=1)
  {
    // memberitahu servo untuk pergi ke posisi  'pos'
    myservo.write(pos);
    // tunggu 15ms untuk pencapaian  posisi servo
    delay(30);
  }
}

void lampuNyala(){
  if(cm > 0 && cm <=30){
    digitalWrite(lampu,HIGH) ;
  }
  else{
    digitalWrite(lampu,LOW) ;
  }
}

Look at your code sequence. An ultrasonic measurement is only taken, when you use pulseIn(). At the end of the loop() function you call your servo() function. In it you tell the Arduino to first go from 0° to 180° and then back to 0°. AFTER THAT (!) the function exits and the loop() function continues. This means, that nothing else happens during the servo motion. The measurement only takes place between the motions, meaning about every 10s.

To solve this problem you need to make the servo code non-blocking. It is mostly a bad thing to use delay(), since you cannot do anything else during waiting. Think about how you are backing a pizza. You are not sitting in front of the oven the whole time, until the pizza is ready. Instead you are looking at your clock regularily and check, if it is time to take the pizza out of the oven.

You can do the same thing on an Arduino with the millis() function. It will return the milliseconds since the last reset/powerup of the Arduino. This has to be used as a clock. To do something after a specific time you first save the current time in a timestamp:

unsigned long timestamp=0;
...
timestamp = millis();

Then in the loop() function you are regularly (on every loop iteration) checking, if the difference between the timestamp and the current time is above your set interval:

if(millis() - timestamp > 30){
    // do something here, like moving a servo
    timestamp = millis(); //update timestamp for next event
}

The Arduino will not do the things simultaneously, but will switch between the different code parts so fast, that it will seem simultaneous. Also refer to the BlinkWithoutDelay example of the Arduino library.

Note: The current delay between two consecutive servo values is ok. If you want to go way faster with the servo, you have to watch out, that the rest of the code in loop() doesn't take to long. If this happens and you cannot make the other code parts non-blocking too, you can also do the servo part in an interrupt routine from a timer.


Arduino raise the error: `does not name a type` when an Object is used outside of the main two blocks setup and loop I have this:

class Person{
public:
    int age;
};

Person p;
p.age;

void setup() { ... }

void loop() { ... }

And I got this error:

Compiling 'MyProgram' for 'Arduino Mega w/ ATmega2560 (Mega 2560)'
MyProgram.ino:18:1: error: 'p' does not name a type
Error compiling

But is I use the Person instance inside setup or loop functions it compiles find.

void setup() {
    // initialize digital pin 13 as an output.
    Person p;
    p.age;
}

I got this:

Compiling 'MyProgram' for 'Arduino Mega w/ ATmega2560 (Mega 2560)'
Binary sketch size: 4,674 bytes (used 2% of a 253,952 byte maximum) (3.45 secs)
Minimum Memory Usage: 428 bytes (5% of a 8192 byte maximum)

What is the different? Why the instance only can be used into the blocks?

I also declared a file with a simple class and then create a instance of it class outside the blocks and I got the same error. If I put the instance inside the blocks it works. So, any tips?

As you have already noticed, you cannot call methods of a class, nor access its properties, outside a "block" (as you call it).  More specifically, you can only perform "programatical" operations from within a function.  Anything outside a function (known as the global scope) is purely for declaration and initialization of variables and types, etc.

Any class variables declared in the global scope have their constructor executed before the rest of the program (even before setup) gets run.  However, setup is not the first function to be called at startup.

Anything you put into a constructor has to take into account the fact that anything might be happening between the constructor being called and the object instance actually being used.  Things like pinMode and digitalWrite are unsafe to use in a constructor, since there is a chance they may be negated during the startup.  That is why the majority of Arduino classes have a .begin() method which is called from setup().

The proper method for using classes with pin control and similar operations is:

The constructor takes the pins to use
The constructor saves those pins in variables
The begin() method is called in setup()
The pins are configured appropriately.

For example:

class myClass {
    private:
        int _myPin;
    public:
        myClass(int pin) : _myPin(pin) {}

       void begin() {
            pinMode(_myPin, OUTPUT);
            digitalWrite(_myPin, HIGH);
        }
};

myClass p(4);

void setup() {
    p.begin();
}

void loop() {
}

The object instance p is in the global scope and can be referenced from any function. The pin is configured only when setup() is run.

The startup sequence, more specifically, is typically this:

The memory used by global and static variables is "zeroed".
Any pre-defined variable values (BSS) are copied from flash into RAM.
Any object constructors are called.
The main() function is called (main startup function).
The init() function is called which configures the Arduino platform.
The initVariant() function is called which performs any board specific setup routines.
USB is configured on the boards that have it
Your setup() function is called.
Your loop() function is called.
The serialEvent() system runs if defined.
Go to 10.

As you can see quite a lot happens between the constructor being called and setup() being called, and you cannot reliably predict what that might be.  Some boards may do nothing more than configure interrupts and enable timers (for things like delay and millis), but other boards may configure IO pins to default settings (especially more complex boards with multiple functions per IO pin), so really the only safe operations you can perform in a constructor are operations which act directly on the internals of the class itself.  Anything outside the scope of the class could be changed before you come to use it.


ESP8266: Client Server Based Home Automation System I am working on a home automation project in which I am trying to use Star Topology, where one esp8266 acts as a server and can be accessed from web browser to receive commands from the user, while two or more esp8266 acts as clients which are connected to relays. Upon the request of user, server esp8266 sends command to the respective client to trigger the relay and the client esp8266 replies with the current status of the relay.

Connections isn't a problem so I am keeping those things aside. So far

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

const char *ssid = "AndroidAP";
const char *password = "qvdo2440";

ESP8266WebServer server(80);
String webPage = "";

void handleRoot() {
  server.send(200, "text/html", webPage);
}

void setup() {
  webPage += "
ESP8266 Web Server
";
  webPage += "
Socket #2 <button>ON</button>
&nbsp;<button>OFF</button>
";

  delay(1000);
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println();
  while (WiFi.status() != WL_CONNECTED) {
   delay(500);
    Serial.print(".");
  }
  Serial.print("Configuring access point...");
  WiFi.softAP(ssid, password);
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
  server.on("/", handleRoot);
  server.begin();
  Serial.println("HTTP server started");
}

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

This is the code for server side. I cannot think of how to program for client side. Any help would be appreciable.

And yes. I have been through many articles, tried out many things which i found on the internet. But nothing could help me. So i am here for few more suggestions with better elaboration.

I agree with most of 'Look Alterno's comment.  So here it is explained in more detail.

Each ESP runs a web server.
Each ESP will handle

GET /root/status
POST /root/change?device=x,state=y

When a client requests /root/status information on each relay managed by the device will be displayed.  For satellite ESPs this will mean displaying live data and for the central on it will mean displaying the last known state (it could also request an update at this time).  If you use an array then presenting this information will be quite simple.

When a client posts a change to a device then the satellite ESPs will change the relay state and the central ESP will forward the message onto the satellite.  It should probably also request a status update to check that the change has occurred.

If you steer clear of hardcoding things and use arrays rather than variable1, variable2, variable3 you should be able to make this expandable.  The biggest problem you will have is registering the satellites with the central device, but you could get around that for now by adding a configure page which had a HTML form that allowed you to enter the IP address of the central device and enter the name of the satellite and the name of the things connected to the relay.

Personally I wouldn't use a PC web server, yes it gives you more processing power, but I don't think you really need it for this, I was surprised how good they were.  If you have issues look at using an ESP32 instead of a ESP8266 for the central node.

I hope that helps


Difference between Arduino and elegoo? I know that Arduino uno and Elegoo uno use chips from the same manufacturarers, but still I was wondering if there's any difference between them in terms of software or similar. In school a professor wants to start making projects with Arduinos and Raspberry pis and etc. So one project we saw online online requires an Arduino uno (the most basic one), but we saw that an Elegoo uno is way cheaper, so we were wondering if the same code could work on both.
Sorry if it's a dumb question, we're basicly newbies.

You should:

Contact Elegoo and ask them if there is any support/return possible.
Consider buying an official Arduino, to support Arduino.
Consider even cheaper options.

Software wise, any "Arduino compatible" board will work with the Arduino IDE, if not, you should return it (if possible).

Some boards may have cheaper hardware and cause issues with:

Serial drivers (some use a cheaper chip, but this often can be fixed)
Input voltage or power stability
Durability (including min/max temperature)

So you should consider if support or the possibility to return a product is more important than paying a little more.


I have made a Nano send 4 pot values to an Uno please help with code Happy New Year!
So I have made a Nano send 4 pot values to an Arduino Uno over serial but I have a problem: I don't know how to separate these values. Here's the code:
Master:
    int Pot = A0;
    int Pot2 = A1;
    int Pot3 = A2;
    int Pot4 = A3;

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

    void loop() {
      int Value = analogRead(Pot);
      int Value2 = analogRead(Pot2);
      int Value3 = analogRead(Pot3);
      int Value4 = analogRead(Pot4);
      Serial.write(Value); //Write the serial data
      Serial.write(Value2); //Write the serial data
      Serial.write(Value3); //Write the serial data
      Serial.write(Value4); //Write the serial data
      delay(150);
    }

Slave:
    int incomingByte; // for incoming serial data

    void setup() {
      Serial.begin(115200); // opens serial port, sets data rate to 9600 bps
    }

    void loop() {
      // send data only when you receive data:
      if (Serial.available() > 0) {
        // read the incoming byte:
        incomingByte = Serial.read();

        // say what you got:
        Serial.print("I received: ");
        Serial.println(incomingByte, DEC);
      }
    }

And a bit from the serial logs:

    I received: 255
    I received: 247
    I received: 11
    I received: 0

It updates and sends these four values for the four pots, it can read them but they are together, and it sometimes also kind of lags if I can say it like that; it sometimes takes longer to update but then it goes to normal again.
Thanks!

If your goal is to "talk" to a computer vs. a human, then a format that can be parsed easily is better than one that is easy to read.
For example, you have:
I received: 255
I received: 247
I received: 11
I received: 0

While this could be parsed by your Uno, it will be a lot simpler if you send the data something like:
255|247|11|0

Now you can use a "C" string parsing function like strtok() to parse on the "|" character.  Of course there are many other ways to do this as well but this is one possible solution to your question.


Where is Arduino.h on a Mac? Can I download a copy if missing? I have installed the IDE on a Mac. It works great. I want to use Eclipse as an editor only. Some files I have include "Arduino.h". Where is this file? I cannot find it.

If it is built in to the tools can I download a copy of this file(s)?

On a Mac the Arduino.h file is within the Arduino application itself. It's not that easy to get to without resorting to the command line.

You also need far more than just Arduino.h - you need the entirety of the Arduino AVR core, which is a collection of .h, .c and .cpp files. They are all together in the application.

You would probably be best off getting them from the github repository (https://github.com/arduino/Arduino) - the files you need are all under hardware/arduino/avr

On your Mac you may find them as /Applications/Arduino.app/Contents/Resources/hardware/arduino/avr or somewhere similar (not entirely sure where it puts it within the app).


Arduino Uno and Arduino Yun software. Which version of the IDE works with both best? I have been working with Unos and just started working with Yun. I have 1.86 currently installed but the Yun starts up saying to use 1.5.6-r2 Beta IDE. Should I uninstall 1.8.6 and install 1.5.6-r2?

Thanks for your help.

Lisa

The Yun startup was written when the normal IDE didn't support the yun, so you had to use a release candidate of a future version.

Those days are long gone.

Always use the latest version of the IDE.


ATtiny85 serial communication, bootloader and setting up fuses I have been reading some articles about ATtiny and how to burn the bootloader. And I have two questions which I can't figure out.

Do I need to manually setup fuses to run 8 MHz on my ATtiny when I'm using my Arduino board as my ISP (there we can select the internal clock and that confuses me)?
For the SoftwareSerial.h library, do I need to setup my ATtiny to 8 Mhz in order to work?

If you search the internet, you mostly find statements, that the fuses will be set right, if you burn the bootloader from the IDE. However I had to set the fuses in an extra call to avr-dude, because the clock divider was still active, setting the clock effectivly to 1MHz, instead of the intended 8MHz. With a command like

avrdude -P /dev/ttyUSB1 -b 19200 -c avrisp -p attiny85 -v

you can read the current fuses. Note that you have to set the parameters according to your setup (I used an ArduinoAsISP on the serial port ttyUSB1). You can write the fuses with a command like this:

avrdude -P /dev/ttyUSB1 -b 19200 -c avrisp -p attiny85 -v -U lfuse:w:0xE2:m

depending on which fuse you want to set, you have to replace lfuse with hfuse or efuse.

SoftwareSerial should also work with other clock frequencies, but I don't know the limitations. Keep in mind, that lower clock frequency means you can only reach lower baudrates. It is crucial, that the fuses are set correctly for the intended speed, because the library takes the speed defined in the IDE. In my case this was 8MHz, but the ATTiny still run at 1MHz, which confused the serial communication.


Merging strings and constants causing scope errors I'm getting a few errors when merging strings with constants.

Here's the pertinent code...

#define STATION_ID ABC123
#define STATION_PASS XYZ987

void loop(){
    String path = "/weatherstation/updateweatherstation.php?ID="+STATION_ID+"&PASSWORD="+STATION_PASS+"&dateutc=now&tempf="+celsiusToFahrenheit(temperature)+"&humidity="+String(humidity)+"&action=updateraw";
}

And then the errors...

weather.cpp:15:20: error: 'ABC123' was not declared in this scope
weather.cpp:64:66: note: in expansion of macro 'STATION_ID'

weather.cpp:16:22: error: 'XYZ987' was not declared in this scope
weather.cpp:64:90: note: in expansion of macro 'STATION_PASS'

Not sure where I'm going wrong on this.

Maybe? Not sure, but give this a try.

#define STATION_ID "ABC123"
#define STATION_PASS "XYZ987"


How to install your own library with Arduino IDE 1.8.5? I'm struggling a bit with Arduino language + its IDE not being 100% real C++. I wrote my own I2C library for a sensor but can't get the IDE's compiler to recognise it. I'm using Ubuntu 18.04.

I get no such file or directory for all of these things I've tried:

Include the .h file by absolute and relative path in the .ino code
Put .cpp +  .h files in ~/Arduino/libraries
Put .cpp +  .h files in ~/sketchbook/libraries
Put .cpp +  .h files in ~/sketchbook/libraries/mylibrary
Put .cpp +  .h files in ~/sketchbook/libraries/mylibrary and try to "install" the library in the IDE (Sketch -> Include library -> Manage libraries; it's not listed)

I'm following the official guide here. Any ideas on how to get the compiler to recognise my library?

You need to:

Create the folder ~/Arduino/libraries/MyLibrary
Place the library files in there named as:

~/Arduino/libraries/MyLibrary/MyLibrary.h
~/Arduino/libraries/MyLibrary/MyLibrary.cpp

Restart the IDE if it is running
Use #include <MyLibrary.h> in your sketch

This is assuming your sketchbook is set to ~/Arduino - change that to wherever the sketchbook is set to (check in Preferences for that location).

Note that in Linux capitalisation is important. The filesystem is case sensitive, and the name of your folder should have the same name and capitalisation as the name of your header file.


Arduino Pro Mini name in CMakeList.txt in CLion I recently try to get my Arduino Pro Mini (5v 16mhz)running in Clion.

I tried to set up the CMakeList.txt but I get the following error:

  Error:Can not find f_cpu in boards.txt for Arduino board ID (pro),
  aborting.

I used the following configuration:

set(${CMAKE_PROJECT_NAME}_BOARD pro)

In the boards text, located at C:\Program Files (x86)\Arduino\hardware\arduino\avr\boards.txt I found the following lines:

pro.name=Arduino Pro or Pro Mini

pro.upload.tool=avrdude
pro.upload.protocol=arduino

pro.bootloader.tool=avrdude
pro.bootloader.unlock_bits=0x3F
pro.bootloader.lock_bits=0x0F

pro.build.board=AVR_PRO
pro.build.core=arduino
pro.build.variant=eightanaloginputs

## Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328
## -------------------------------------------------
pro.menu.cpu.16MHzatmega328=ATmega328 (5V, 16 MHz)

pro.menu.cpu.16MHzatmega328.upload.maximum_size=30720
pro.menu.cpu.16MHzatmega328.upload.maximum_data_size=2048
pro.menu.cpu.16MHzatmega328.upload.speed=57600

pro.menu.cpu.16MHzatmega328.bootloader.low_fuses=0xFF
pro.menu.cpu.16MHzatmega328.bootloader.high_fuses=0xDA
pro.menu.cpu.16MHzatmega328.bootloader.extended_fuses=0x05
pro.menu.cpu.16MHzatmega328.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

pro.menu.cpu.16MHzatmega328.build.mcu=atmega328p
pro.menu.cpu.16MHzatmega328.build.f_cpu=16000000L

So I'm wondering what Boardname to use, to get the Pro Mini working. Thanks in advance!

The problem here is that the Pro Mini comes in a number of variants for different voltages / speeds etc. The different variants are selected using a menu in the IDE.

CLion doesn't know about those menus, nor how to find the f_cpu from the right one for your board.

So there are two solutions:

Create your own board entry for the Pro Mini without the menu entries.
Use an earlier version of the IDE that has the Pro Mini boards as separate entries (basically any version before the menu system was created).

If you want the latest API then you will have to go route 1. That could be as simple as modifying the existing pro.* entries to remove the menu and replace that section with just the flags that are set by the correct menu (basically remove all the pro.menu.* entries except the ones for your board, then remove the menu.cpu.<whatever>. from each of the lines, as well as the entire menu entry name line.)

So you would basically change these lines:

## Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328
## -------------------------------------------------
pro.menu.cpu.16MHzatmega328=ATmega328 (5V, 16 MHz)

pro.menu.cpu.16MHzatmega328.upload.maximum_size=30720
pro.menu.cpu.16MHzatmega328.upload.maximum_data_size=2048
pro.menu.cpu.16MHzatmega328.upload.speed=57600

pro.menu.cpu.16MHzatmega328.bootloader.low_fuses=0xFF
pro.menu.cpu.16MHzatmega328.bootloader.high_fuses=0xDA
pro.menu.cpu.16MHzatmega328.bootloader.extended_fuses=0x05
pro.menu.cpu.16MHzatmega328.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

pro.menu.cpu.16MHzatmega328.build.mcu=atmega328p
pro.menu.cpu.16MHzatmega328.build.f_cpu=16000000L

to this:

## Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328
## -------------------------------------------------
pro.upload.maximum_size=30720
pro.upload.maximum_data_size=2048
pro.upload.speed=57600

pro.bootloader.low_fuses=0xFF
pro.bootloader.high_fuses=0xDA
pro.bootloader.extended_fuses=0x05
pro.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

pro.build.mcu=atmega328p
pro.build.f_cpu=16000000L

and delete all the other pro.menu entries.


Arduino Mega prototype analog timer interrupts: newbie question I am currently using an Arduino Mega with a fast vibration sensor to trigger the components operation (force sensor, temperature sensor) and also toggle sleep mode.

I am very new at this and I have been doing some googling, but I just can't seem to understand it.

So, my questions are:

How would I toggle(on/off) sleep mode?
How would I use interrupts (timer, pin change interrupt?) for an analog pin that triggers when the vibration sensor is triggered, resulting in other components operating?

I am currently working on a Mega, but I will eventually move on to the Arduino Mini Pro. I hope there are no exclusive problems later on.

I realize that this is not a professional question, but I find these tasks very challenging.

Please help me. An example link or perhaps example code to help me understand better.

Thank you very much.

How would I use interrupts (timer, pin change interrupt?) for an analog pin that triggers when the vibration sensor is triggered, resulting in other components operating?

Thee best and most authoritative answer to that and all your other questions about the chip can be found in thee device data sheet and the compiler manual. Read them thoroughly and then write code to the data sheet to experiment.

Your can fire example have an analog interrupt where the chip constantly does ADC on the pin attached to the sensor and you can test the value of the ADC to see if certain trigger conditions are met and take appropriate actions.

The same with timers, etc. The data sheet is your best friend.


If I put a shield on an Arduino, can I use the Arduino for anything else? I did some basic Arduino examples in the recent past, but I have never actually seen a shield for Arduino firsthand.

So I wonder: If I put a shield on an Arduino (for example, the Adafruit Motor Shield), does it "block" the entire Arduino, including all input and output pins?

Is it possible to use a shield, and still connect additional components that would usually connect directly to the Arduino (say, a potentiometer, or anything similar)? Does this depend on the type of Arduino, or on the type of the shield, or is it not possible at all?

Normally, yes, you may plug other components to your setup after you plug your shield, but it depends on the shield exposing the unused Arduino pins through additional female headers.

Some shields even provide a little protoboard or perfboard to make it convenient for plugging or soldering additional components. Below are some examples:

Arduino shields are normally designed to be stackable, so you can plug one on top of the other. See more on Arduino shields from this WikiPedia article. See below one example of stacked shields, shamefully stolen from this great answer by RedGrittyBrick.

Photo by John Boxall

But note that you need to study carefully what pins each of the shields use to avoid conflicts between the boards. Such conflicts may lead to damages.


How to find out the maximum used stack space? I am creating an Arduino sketch which involves quite some classes, and I want to check if it will run on an Arduino Uno or Mega (2 KB vs 8 KB SRAM).

So far my global variables take up around 1,200 bytes, and I expect this will rise. However, beyond that I need to make sure the stack memory is not using up too much. How can I find the maximum used stack size?.

I can check manually by calculating the maximum function stack and calculating all parameters + local variables, but this is a very tedious job (especially since my application changes still a lot).

Or another way: I know it is possible to get the free space, but should I add this in 'strategic' locations or in the beginning of all functions and continue from there? (there will be many of them).

Or is there preferable some static way of checking this?

The application works within Visual Studio C++ as stand alone too, so maybe that helps for some solution.

I expect the stack size easily to be a few hundred bytes (which is quite a lot for the Arduino Uno SRAM).

Knowing the stack size is pretty easy: the stack pointer is initially
set to RAMEND and goes down as the stack grows. Thus:

static inline size_t stack_size()
{
    return RAMEND - SP;
}

  should I add this in 'strategic' locations [...]

Obviously, the result will depend on where this is evaluated. Ideally
you should test this in the deepest parts of your call chain, as this is
where the stack will be at its maximum size. Note that ISRs stack on top
of all your regular code.

Edit: There is no easy way to know the maximum stack size. You
could get an approximation by sampling the stack at regular intervals,
e.g.:

#include <util/atomic.h>

volatile size_t min_sp = RAMEND;

ISR(TIMER0_COMPA_vect)
{
    if (SP < min_sp)
        min_sp = SP;
}

static inline size_t max_stack_size()
{
    size_t min_sp_copy;
    ATOMIC_BLOCK(ATOMIC_FORCEON) {
        min_sp_copy = min_sp;
    }
    return RAMEND - min_sp_copy;
}

If you enable TIMER0_COMPA interrupt in setup():

TIMSK0 |= _BV(OCIE0A);

then the stack size will be sampled every 1.024 ms. Note, however,
that this ISR is itself using some stack space for its own purposes
(9 bytes in my experiment), and that this is not sampling other
ISRs or critical sections.


Shaft Encoder Accuracy So, first of all I just want to point out this code is from: Reading Rotary Encoders and is not mine.

I have a magnetic shaft encoder mounted on a regular DC motor, my problem is that I cannot receive the exact angle of the motor. The encoder outputs +1 each 90 degrees (I then multiply by 90). And is there any relationship between valx, valy, valz and the angle?

#define encoder0PinA 2
#define encoder0PinB 3
int rounds= 0;
volatile unsigned int encoder0Pos = 0;
unsigned int tmp_Pos = 1;
unsigned int valx;
unsigned int valy;
unsigned int valz;

boolean A_set;
boolean B_set;

int enA = 9;
int in1 = 10;
int in2 = 11;

void setup() {

  pinMode(encoder0PinA, INPUT);
  pinMode(encoder0PinB, INPUT);
  // encoder pin on interrupt 0 (pin 2)
  attachInterrupt(0, doEncoderA, CHANGE);

  // encoder pin on interrupt 1 (pin 3)
  attachInterrupt(1, doEncoderB, CHANGE);
  Serial.begin( 9600 );

  pinMode(enA, OUTPUT);

  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  analogWrite(enA, 225);
  Serial.begin (9600);
}

void loop(){
//Check each second for change in position

  if (tmp_Pos != encoder0Pos) {
    Serial.print("Index:"); Serial.print(encoder0Pos * 90,DEC);
    Serial.println();
    Serial.print("valx:");Serial.print(valx,DEC);
    Serial.println();
    Serial.print("valy:");Serial.print(valy,DEC);
    Serial.println();
    Serial.print("valz:");Serial.print(valz,DEC);
    Serial.println();
    tmp_Pos = encoder0Pos;
  }
}

// Interrupt on A changing state
void doEncoderA(){

  // Low to High transition?
  if (digitalRead(encoder0PinA) == HIGH) {
    A_set = true;
    if (!B_set) {
      encoder0Pos = encoder0Pos + 1;
      valx=analogRead(0);
      valy=analogRead(1);
      valz=analogRead(2);
    }
  }

  // High-to-low transition?
  if (digitalRead(encoder0PinA) == LOW) {
    A_set = false;
  }
}

// Interrupt on B changing state
void doEncoderB(){

  // Low-to-high transition?
  if (digitalRead(encoder0PinB) == HIGH) {
    B_set = true;
    if (!A_set) {
      encoder0Pos = encoder0Pos - 1;
    }
  }

  // High-to-low transition?
  if (digitalRead(encoder0PinB) == LOW) {
    B_set = false;
  }
}

If the encoder only gives +1 pulse per 90 degrees, you aren't going to get better than 90 degree accuracy out of it.

In the example code at the link, the val{x,y,z} are measured analog variables of some other thing that are sampled at each encoder lcoation:

  My project is a data loger where three analogue inputs are sampled
  each time a rotary encoder pulse steps clockwise. On an Arduino, time
  is of the essence to get this data sampled and saved somewhere (I have
  not included the 'saving somewhere' part of this project yet.) In
  order to save some processor cycles, I have slightly redesigned the
  interrupt system to maintain a pair of boolean states outside of the
  interrupt loop.

These are not directly related to the positioning of the encoder, and there is no reason to think they provide angle information.


Does an I²C IO Expander needs additional resistors for outputs? I have following setup (see also schematic in the end)

Arduino Nano is connected via I²C to the PCF8575C (link) IO Expander.
Both, SCL and SDA have 10kOhm pull-ups to 5V.
The Expander pins are connected to a MOSFET-driver that turns on/off 12V LED stripes.
The Expanders Bus address is set via Expanders A0-A2 pins to 0 (0x20).
The MOSFET driver pins have to be pulled to logic 1 (above 2.2V) in order to turn on the stripe.

Currently Arduino runs an blink example, that turns all Expander IO pins on/off every second (using Arduino Wire Library), but the MOSFET-driver does not turn on/off any Stripe.

I can manually turn on Stripes by connecting MOSFET-driver pins to Arduinos 5V (or 3.3V)

The power supply to the IO Expander is O.K.

By measuring the resistance between GND and IO pins of the Expander, I can see that it alternates every second (so I²C communication to the Expander works also)

Curious thing: While measuring this resistance (holding the multimeter test leads) to GND and to the IO pin of Expander, the MOSFET-driver turns the Stripes on and off! When I take the test leads away it stops working! Magic?!

What am I missing? Do the output pins of the PCF8575C need some extra pullup/pulldown resistors or something else?

Thank you in advance!

Schematics:

Yes, according to the datasheet (which should always be your first port of call for any chip) the outputs are Open Drain. That means you require a pullup resistor, exactly as if the outputs were simple buttons.


Atmega collecting and relaying interrupt calls I like to collect all possible interrupt and relay them to an alternative handler interrupt table what the user can set.

In order to do this i have to:
   1) collect all/any interrup request
   2) identify where is the interruption came from
   3) relay the call to another table the user pointed.

If you familiar with interrupts you know if you registers a single function to all interrupt handler there's no way to idenfity the source of the interrupt.
But registering unique interrupt handler that carries the information of the source and calls another function to dispatch call, for each interrupt is a code space wasting. Eg.: the atmega328 has 24 interrupt handlers. Each of the is compiled with the avr-gcc consumes 76 bytes.

But i have and idea how it is possible to register one handler function and identify the source:

00000000 <__vectors>:
   0:   0c 94 34 00     jmp 0x68    ; 0x68 <__ctors_end>
   4:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
   8:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
   c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>

If i define an interrupt handler (even if it can fit the 4 byte space) a jmp instruction is placed. If it can be replaced to eg.: call 0xa2 (which can fit in 4 bytes), is can be used to identify the interrupt source address.

Because call stores the return address, the function started at 0xa2 can read back that address and therefor idenfity the caller. Then add an extra pop (pop the stack address accumulated by the call at the interrup table) and reti (to return as like from an interrupt handler) after the function body.

If this can work theorically, to achieve this only one question remains:

How can i replace the jmp instructions to call in interrupt table?

The interrupt vector table is provided by the C runtime. It is
not normally intended to be overridden by user code. You can, however,
do it, if you replace the whole C run time by your own, and compile your
sketch with the -nostartfiles option.

I have played this game once I was trying to accurately assess interrupt
latencies. See the details in this answer (the answer is long,
but you can go right to the last section).


Is there an alternative to strtok_r in extracting words from char? The task, in char, I get some data that I have to parse into parts.

In this case, I use strtok_r, which finds identifiers like

  "=", " ", "&"

Code:

char payload[70] = "GET /wifi?ssid=MyWiFi&pass=123456789 HTTP 11";
char *p;
char *i;

void setup() {
  Serial.begin(15200);
  Serial.println("Load");

  p = strtok_r(payload, "=", &i);
  // Get SSID
  p = strtok_r(NULL, "&", &i);
  Serial.println(p);

  p = strtok_r(NULL, "=", &i);
  // Get PASS
  p = strtok_r(NULL, " ", &i);
  Serial.println(p);
}

void loop() {}

Result:

  Load MyWiFi 123456789

This works, but as soon as I add the characters strtok_r works on to the ssid = or pass = value, it stops working, outputting the cropped data.

These characters can be in the name of any WiFi network or the generated password.

Tell me, are there strtok_r analogues, where instead of a single character I can insert a whole phrase?

For example, so that he finds the beginning of ssid by the tag "ssid=", and finishes before "pass=".

Resolved.

Thank you all for your help!

I studied both options from @Majenko and @user7761803. All of them came in handy in various parts of the code.

Perhaps someone will use the Regexp library to parse such data. Here is example:

    #include <Regexp.h>

    char payload[60] = "ssid=MyWifi&pass=ukLPm&I*uwlm HTTP";
    char ssid[25], pass[25];

    void setup() {
      ms.Target(payload);
      char match_result = ms.Match("ssid=(.*)&pass=(.*) H", 0);
      if(match_result == 1) {
       // Get SSID
       ssid = ms.GetCapture(regexp_var.buffer, 0);
       // Get PASS
       pass = ms.GetCapture(regexp_var.buffer, 1);
      }
    }

    void loop() {}

The function you are looking for is strstr(), which takes two strings, and returns a pointer to where the second string appears in the first (or NULL if it doesn't appear).

You could use it something like this:

void setup() {

    Serial.begin(15200);
    Serial.println("Load");

    char *p = strstr(payload, "ssid=");
    char *q = strstr(payload, "pass=");
    char *r = strstr(payload, " HTTP");

    char *ssid = NULL;
    char *pass = NULL;

    if (p == NULL || q == NULL || r == NULL) {
        // One or other (or both) missing - what to do?
    } else {
        *r = '\0';  // Terminate the last string

        // If this really is an HTTP query string, we don't know
        // if ssid or pass will be first
        if (p < q) {    // Terminate the first string
            *(q - 1) = '\0';
        } else {
            *(p - 1) = '\0';
        }

        ssid = p + 5;
        pass = q + 5;

        Serial.println(ssid);
        Serial.println(pass);
    }
}

Note, however, that your payload string looks like an HTTP query string.

These are defined so that they are split at the & characters, and if a & needs to appear in one of the values, it should be percent encoded (where the & would appear as %26, and would need to be decoded afterwards).

However, that wasn't your question...


Moving an item on a pole, can an Arduino work for my project? I'm a computer programmer, but I've never done anything with Arduino. I'd like to build something that holds a polisher (this one, in specific: http://www.homedepot.com/p/BLACK-DECKER-6-in-Random-Orbit-Waxer-Polisher-WP900/202516385) on a metal pole, and moves the polisher up and down (vertically) on the pole at varying speeds (I'd like to use arduino to control the motor/speed)?

Is this the sort of thing Arduino would be able to do? If so, can anyone point me to any motors that would work? If not, any tips on where else I should look?

I am also a software guy by profession. I've always liked tinkering with electronics, and have recently gotten into Arduino. It is an excellent platform for developing hybrid hardware/software solutions for problems like this. It is very easy to use, both hardware and software.

There is a large ecosystem of add-ons called "Shields" that just plug in. You can probably find a motor control shield that will do exactly what you want.

Your biggest challenge, I think, is going to be mechanical. How will you hold the polisher in position, and make a mechanism that will raise and lower it?

Off the top of my head what I come up with is a U shaped metal bar with a threaded rod in the opening of the U. You'd build a "sled" that would grip the bar and would have teeth that would grip the threaded rod. Then your would have a motor on the end of the assembly that would turn the threaded rod to move the sled up and down on the bar. You'd attach the polisher to the sled. You'd probably need a spring or rubber holder so that the polisher would press gently on the surface being polished but with some freedom of motion.


How to interpret accelerometer output data? I'm running my accelerometer through my Arduino mini and outputting my values using the following values

 // print the sensor values:
  Serial.print(analogRead(xpin));
  // print a tab between values:
  Serial.print("\t");
  Serial.print(analogRead(ypin));
  // print a tab between values:
  Serial.print("\t");
  Serial.print(analogRead(zpin));
  Serial.println();
  // delay before next reading:
  delay(100);

Here's an example.

The x,y,z values that are outputted are quite high even the arduino is not moving. I'm new to Arduino programming and would love some understanding on how to convert these x,y,z to an Acceleration value ie. Is the arduino moving or not?

The accelerometer will output a specific number of volts (or millivolts) per g.  You need to find that information in the datasheet for your accelerometer.

Then you need to take the readings you make through analogRead() and convert them to a voltage. Then that voltage can be used, combined with the value you found above, to determine the g reading.


Supplying power to arduino by 5V and 2A adapter Can I power my Arduino using a 5V/2A adapter by connecting it through the USB port?

More precisely, I have to run a module requiring 200mA but the aim is to make the laptop independent.

Amps are not "forced" through a circuit like volts are. A closed circuit draws as much power (in amps) as it needs, so the only problem you could ever have is having too little current and not too much. Seeing as your module draws 200ma 2 amps to power it is plenty.


Arduino Prototype on Breadboard: "avrdude: stk500_recv(): programmer is not responding" I have created an arduino prototype using the exact instructions found on this page:

https://www.arduino.cc/en/Main/Standalone

However, when I plug in the micro USB power supply and try to upload a program, here's the error I get:

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe0

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0

I have tried the following solutions, to no avail:
1) press the restart button (in a variety of ways and lengths of time)
2) Enable verbose output
3) trying the different board types in the Arduino IDE
4) Checking the COM port

I have no idea what to do I've basically tried everything I could find, on this website and others.

I hope you guys can help! Thanks very much :)

Remove the pins connected to Tx and Rx while uploading the code , it worrked for me.
also include all the libraries currently used in your program.
Good luck!!


adding a dead band to my motor and gearbox I have a motor and gearbox that has limits and a pot built in.

I have some code what drives the motor one way to when it hits its limits takes a value and drives the other way and takes a value, then map the range from 0 to 100, that all works fine.

I also have a analog input map to 0 to 100 what I would like to do is to drive the motor to where ever the analog input is at, which is what I have done with the code below but when the motor gets close it starts hunting backwards and forwards.

I tried to add some sort of dead band (where + 0.5 / where - 0.5) it just seems to just move the problem.

I did try -+ but this still did not help, so what I need to do is aim for the target value and stop then if I'm within 0.5 ether way then that is good enough.

How can I do that?

sensor       = pot on motor,
where        = 0 to 5 input,
vent1UPlim   = limits,
vent1DOWNlim = limits

PS. I know the map of 0 to 100 could do with being bigger but it's just easier to get my head around at the moment.

        //            pot           0-10v     ONE WAY
          if (sensorValue > (where + 0.5)) {
          if (digitalRead(vent1UPlim)==    HIGH) {
            DoneInitializationA=false;
            digitalWrite(vent1enable,      HIGH);
            delay(50);
            digitalWrite(vent1PWMA ,       HIGH);
            mydisp.drawStr(0, 2, "-close-|");
          }
          else {
            digitalWrite(vent1PWMA ,       LOW);
            delay(50);
            digitalWrite(vent1enable,      LOW);
            mydisp.drawStr(0, 2, "       |");
          }
        }
        else {
          if (!DoneInitializationA)
          {
            digitalWrite(vent1PWMA ,       LOW);
            delay(50);
            digitalWrite(vent1enable,      LOW);
            mydisp.drawStr(0, 2, "       |");
            DoneInitializationA=true;
          }
        }

           //                                   OTHER WAY
          if (sensorValue < (where - 0.5)) {
          if (digitalRead(vent1DOWNlim)==  HIGH) {
            DoneInitializationB=false;
            digitalWrite(vent1enable,      HIGH);
            delay(50);
            digitalWrite(vent1PWMB ,       HIGH);
            mydisp.drawStr(0, 2, "-open -|");
          }
          else {
            digitalWrite(vent1PWMB ,       LOW);
            delay(50);
            digitalWrite(vent1enable,      LOW);
            mydisp.drawStr(0, 2, "       |");
          }
        }
        else {
          if (!DoneInitializationB)
          {
            digitalWrite(vent1PWMB ,       LOW);
            delay(50);
            digitalWrite(vent1enable,      LOW);
            mydisp.drawStr(0, 2, "       |");
            DoneInitializationB=true;
          }
        }

The simple way is to just subtract one from the other, take the absolute value and see if it exceeds your hysteresis range.

eg.

if (abs (sensorValue - where) >= 0.5) {
  {
  // do something

  if (sensorValue > where)
    {
    // one way
    }
  else
    {
    // other way
    }
  } // end of large enough to worry about

In response to this (since deleted):

  would this not have the same problem as mine as instead of hunting round its target it will just do it 0.5 away from the target?

By subtracting and taking the absolute value, we create a band of +0.5 and -0.5 where, if the sensor is in that range, we do nothing. It hasn't moved the problem because it can't move in two directions at once (both up and down).


How to calculate illuminance from the output of a TCS34725 color sensor? I am using Arduino UNO with the sensor with the following programm.

#include <Wire.h>

// TCS34725 I2C address is 0x29(41)
#define Addr 0x29

void setup()
{
  // Initialise I2C communication as MASTER
  Wire.begin();
  // Initialise Serial Communication, set baud rate = 9600
  Serial.begin(9600);

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select Wait Time register
  Wire.write(0x83);
  // Set wait time = 2.4 ms
  Wire.write(0xFF);
  // Stop I2C Transmission
  Wire.endTransmission();

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select Atime register
  Wire.write(0x81);
  // Atime = 700 ms, max count = 65536
  Wire.write(0x00);
  // Stop I2C Transmission on the device
  Wire.endTransmission();

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select control register
  Wire.write(0x8F);
  // AGAIN = 1x
  Wire.write(0x00);
  // Stop I2C Transmission
  Wire.endTransmission();

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select enable register
  Wire.write(0x80);
  // Power ON, RGBC enable, wait time disable
  Wire.write(0x03);
  // Stop I2C Transmission
  Wire.endTransmission();
  delay(800);
}

void loop()
{
  unsigned int data[8];

  // Start I2C Transmission on the device
  Wire.beginTransmission(Addr);
  // Select data register
  Wire.write(0x94);
  // Stop I2C Transmission on the device
  Wire.endTransmission();

  // Request 8 byte of data from the device
  Wire.requestFrom(Addr, 8);

  // Read 8 bytes of data
  // cData lsb, cData msb, red lsb, red msb, green lsb, green msb, blue lsb, blue msb
  if (Wire.available() == 8)
  {
    data[0] = Wire.read();
    data[1] = Wire.read();
    data[2] = Wire.read();
    data[3] = Wire.read();
    data[4] = Wire.read();
    data[5] = Wire.read();
    data[6] = Wire.read();
    data[7] = Wire.read();
  }

  // Convert the data
  float cData = (data[1] * 256.0) + data[0];
  float red = (data[3] * 256.0) + data[2];
  float green = (data[5] * 256.0) + data[4];
  float blue = (data[7] * 256.0) + data[6];

  // Calculate the final lux
  float luminance = (-0.32466 * red) + (1.57837 * green) + (-0.73191 * blue);

  // Output data to serial monitor
  Serial.print("Red color Luminance   : ");
  Serial.print(red);
  Serial.println(" lux");
  Serial.print("Green color Luminance : ");
  Serial.print(green);
  Serial.println(" lux");
  Serial.print("Blue color Luminance  : ");
  Serial.print(blue);
  Serial.println(" lux");
  Serial.print("IR Luminance          : ");
  Serial.print(cData);
  Serial.println(" lux");
  Serial.print("Ambient Light Luminance : ");
  Serial.print(luminance);
  Serial.println(" lux");
  delay(500);
}

Is the output really in lux or is it counts? If it's counts, how can I calculate the illuminance in lux?

In the chip's datasheet on page 8 in the chapter "RGBC Operation" (emphasis by me):

  The RGBC engine contains RGBC gain control (AGAIN) and four
  integrating analog-to-digital converters (ADC)for the RGBC
  photodiodes. The RGBC integration time (ATIME) impacts both the
  resolution and the sensitivityof  the  RGBC  reading.  Integration  of
  all  four  channels  occurs  simultaneously  and  upon  completion  of
  theconversion cycle, the results are transferred to the color data
  registers. This data is also referred to as channelcount.

So, if you read the values from the data registers, you get simple count values, which were determined by the ADCs connected to the channels. To get a value in lux, you need to calculate that yourself.

Adafruit has a library for their breakout board with this chip. In their tutorial it seems, that the library outputs a value in lux. Maybe you can also use this library, or you can check, how they are converting the values from the sensor to lux values.


ArduCAM OV2640 and microSD card module -- SPI problems So what I'm trying to do is use the ArduCAM OV2640 (2MP Mini) to take a timelapse. Of course the first thing I have to do it to get it to take a picture and write it to an SD card. The thing is, the camera works fine by itself, however when I hook up the SD card something happens where the SPI no longer works (I have a general understanding of how SPI works -- not a highly technical understanding though).

So my main question is if it's possible for a device using SPI to 'use up' the entire SPI bus so that other peripheral devices can't interact with the microcontroller?

And if so, is there any software or way to visualize this? Like something that monitors the SPI bus?

And as for how to actually fix the problem, would it be practical to use a shield with a built in SD card module? Or use a logic gate to determine which device to allow access?

I really don't have the greatest understanding of this, so any help would be appreciated.

EDIT:

I'm using this camera module with this sd card module. As for my wireup, the camera follows as below:

The common pins between the SD card module and camera are VCC,GND,MISO (pin 12) , MOSI (pin 11), and SCK (pin 13). I have an individual CS pin for each.

In this case, I don't think that a device is "using SPI to 'use up' the entire SPI bus so that other peripheral devices can't interact with the microcontroller". I think that your problem probably lies with how your SD card is connecting via the SPI bus.

The problem is that a lot of Serial Peripheral Interface (SPI) devices, particularly the cheaper ones, don't properly put the MISO pin into high-impedance when SS is pulled high.

I had almost exactly this situation with one of my projects. I eventually resolved it by placing a tri-state buffer in the MISO line for each of the SPI devices.

In that case, I used a 74HC125 (4-channel tri-state buffer).

This is the page on Better SPI Bus Design in 3 steps that finally got me on the right track. I think the explanations are reasonably clear (at least compared with many other sites I found!).


Digital pins on Arduino function as both positive and negative terminals? I'm learning the arduino platform and working on a circuit that connects the two pins of a piezo buzzer -- one to ground and the other to a digital pin of the arduino board. In this configuration, is the arduino's digital pin acting as the positive terminal of the circuit?

The arduino docs seem to suggest it is:

  They (the digital pins) can provide a substantial amount of current to other >circuits. Atmega pins can source (provide positive current) or sink (provide >negative current) up to 40 mA (milliamps) of current to other devices/circuits.

Can the digital pins act as both positive and negative terminals in circuits? Does this question even make sense? What resources are out there that can help me better understand the underlying electronics of the arduino and microcontrollers in general?

The answer to your question is basically yes, you can use ATmega I/O pins as +/- power supply terminals for other circuits. But there's a limit to what you can power that way (20mA per pin and 100mA total per ATmega). In practice this means you can only power the simplest circuits (single LEDs per pin, and not many LEDs in total, for example). As a general rule, you should really look for other ways to power anything else.

Also, there's a problem with the citation you gave. That 40mA figure is the absolute maximum current per pin, but that should be avoided. Safest is to use about 20mA of maximum current per pin. Also, the ATmega pins should not have more than 200mA flowing through Vcc and GND (also an absolute maximum that should also be avoided).

Usually, you should either power other stuff off of the regulated +5V that also feeds the ATmega (up to the regulator capacity that depends on the Arduino board - 500mA for the Arduino Uno - 1A for LM7805 regulators - and so on). You could also use the unregulated power in some cases. Then you should use digital pins on the ATmega to switch transistors on and off which in turn will switch your load. Sometimes you can use transistors to switch relays, that in turn will switch even larger loads.


Exception Handling with the Arduino IDE I'm using a port of the STL found here and trying to debug with a simple try{...}catch{...} loop. When compiling with the Arduino IDE, I get the error message

  exception handling disabled, use -fexceptions to enable.

I'm not quite sure what this means. Can the Arduino simply not support exceptions? Or is -fexceptions a compiler flag I can enable?

As you have already found out, add -fexceptions to the compiler flags. This can be done by modifying the platform.txt of your Arduino IDE installation.

See https://github.com/arduino/ArduinoCore-avr/blob/master/platform.txt#L28. There is -fno-exceptions defined, so you have to remove that, too.


HC-05 Bluetooth Module - INQ-Command doesn't work For a project I need to connect a Bluetooth Remote control with an Arduino Nano.

The Problem

I am trying to setup a connection to said Bluetooth remote Control. This device is visible! (I have confirmed it with a smartphone)

Here are the steps that I am trying to do with the Arduino and HC05 module:

AT <-- confirms, that Command Mode is running successfully
OK

AT+ROLE? <-- 1 For Bluetooth Master Mode
+ROLE:1
OK

AT+CMODE? <-- 1 allows connecting to any BT address
+CMOD:1
OK

AT+INQM? <-- Show Inquiry access values
+INQM:1,1,48
OK

AT+INQ <-- Inquiry Bluetooth Device

After ~60 seconds, it just says "OK", but according to this tutorial  or according to this youtube video it should display all Bluetooth-devices, that are ready to connect.
The BT device is definately visible. (I tried multiple BT devices like smartphones and peripheral devices).

Why is the inquiry not working? What is wrong here?

The circuit is exactly like in this picture:

For setting up the Bluetooth-connection I wire the EN-Pin to +3,3V, which successfully activates AT-Command-Mode
According to this site, you can do it like that.

Here is my code, that I use, to communicate with the module. - It works good!

#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); // RX | TX
// Connect the HC-05 TX to Arduino pin 2 RX.
// Connect the HC-05 RX to Arduino pin 3 TX through a voltage divider.
//

char c = ' ';
int buf[64]; //buffer to store AT commands
int len = 0; //stores the length of the commands

void setup()
{
    Serial.begin(9600);
    Serial.println("Arduino is ready");
    delay(500);
    mySerial.begin(9600);
    Serial.println("BlueTooth is ready");
}

void loop()
{

  if(Serial.available())
  {
    len = Serial.available(); //store number of bytes to read
    for(int i = 0; i<len; i++) //store all bytes into the buffer
    {
      buf[i] = Serial.read();
    }
    for(int i = 0; i<len; i++)
    {
      mySerial.write(buf[i]);
      Serial.write(buf[i]);
    }
  }

  if(mySerial.available())
  {
    len = mySerial.available();
    for(int i = 0; i<len; i++)
    {
      buf[i] = mySerial.read();
    }
    for(int i = 0; i<len; i++)
    {
      Serial.write(buf[i]);
    }
  }

}

Here is a related question but the answer doesn't help.

I did a factory reset of the device. That resolved the issue

AT+ORGL
AT+RESET

Another thing that is very important: The KEY-Pin (EV-Pin on some boards) must be HIGH (3Volts), during the INQ-command. If this PIN is not High, the inq-command will not work.

If you put 3V to this PIN and release it, you indeed are in AT-Command mode. But not all AT-commands work (e.g. the said at+inq command). If you want to enable all AT-commands the PIN must remain high.


Distance finder technology 0-24inches Can anyone point me towards whats best for relatively low cost distance measuring in the 0-36" range (or 0 - 1m range) with 1/16"/1mm accuracy.  My initial approach was going to be to hack a laser tape measure, but wanted to know if that was the best in cost vs accuracy.

Essentially looking to measure how close I am to a stationary metal plate.

Thanks for any help.

You will likely find the best accuracy is derived from a laser-based measurement. My Bosch is laser only, no ultrasound component and has 1/16" resolution. For your application, the six inch minimum distance limitation of the Bosch is outside your specifications.

Because laser measurement devices use time versus distance, it's possible you could construct a mirror chamber with front-surface mirrors that would cause the laser to travel six inches before exiting the chamber, overcoming that limitation. The calibration should be straight-forward, as you'd place the chamber flush and adjust your mirror placement until you read the exact expected compensation distance.

You would need only small mirror panes, which would not "break the bank," but if you find a discarded large-screen projection television, the mirror within is front surface and quite large. Front surface mirrors should not have contamination from touching and should be cleaned with care, as you can erode or otherwise degrade the reflective surface.

I found this site:
http://blog.qartis.com/arduino-laser-distance-meter/
which looks promising for a different model of laser rangefinder, although the creator has run into a stumbling block or two.

It would appear that the key is to overcome the minimum distance limitation, perhaps as I suggested above, and interfacing with serial communications of the arduino.

One of the links I pursued involved the creator contacting the technical support of the manufacturer. The support ticket was closed as "resolved," in the manner of advising the user that the warranty was void by opening the case. Yeah, like that matters to makers and hackers!


ESP8266 - Webserver not working in loop I have simple example, where in loop is called webServer to handle clients and also text drawing on display.
The thing is that webServer is not responding, but when I remove second part of loop - drawing text to display then web server starts to work normally.

Server does not respond:

 void loop() {
      server.handleClient();
      unsigned long timeNow = millis();
      if ((timeNow > screenChangeTime))  {
          display.clear();
          display.setFont(ArialMT_Plain_16);
          display.setTextAlignment(TEXT_ALIGN_CENTER);
           display.drawString(12, 20,"Loaded: "+String(particles));
           screenChangeTime= timeNow + delay;
           display.display();
      }
    }

Server responds:

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

My guess is, that you're wasting too much time within the drawing-part.

What is the value for delay? I guess you have a number too low chosen here. And you should really set this new time after you have updated the display by display.display();.

Your webserver doesn't respond because he's not called often enough inside this code.


Weird multiplication result Here's come Arduino code.

#define M(x, y) x * y;
void setup() {
  Serial.begin(9600);
  Serial.println(M(3 + 2, 4 + 2));
}
void loop() {
}

Why is the result 13?

Because M(3 + 2, 4 + 2) gets replaced to 3 + 2 * 4 + 2 and then the normal priority of operations does the multiply before the addition.

This is one of the many reasons why you should prefer functions over macros. The inliner of the compiler will negate any call overhead.

If you truly want to use a macro then surround each use of the macro arguments in parenthesis, surround the macro itself in parenthesis as well.

#define M(x, y) ((x) * (y))


Humidity values returned by DHT22 sensors failing after some time I've built a weather station using Arduino that measures temperature/humidity and pressure using an Adafruit 8266 HUZZAH. Temperature and Humidity are measured using a DHT22 sensor a ordered from AdaFruit. The project was completed about 4 months ago and for the first three months has returned what appears to be good data. Eventually, the humidity values started returning garbage, values around 1%.

I replaced the DHT22 sensor with another, this time from a random eBay seller. This also worked fine for about a week (humidity values appear to look good in the 20-60% range).

Then all of a sudden, they dropped to 1% again.

If I run the DHTtester program (instead of my program) against the sensor and my Uno development board, the result is also 1% humidity for this sensor.

 DHTxx test!
 Humidity: 1.00 %   Temperature: 19.20 *C 66.56 *F  Heat index: 17.96 *C 64.33 *F
 Humidity: 1.00 %   Temperature: 19.20 *C 66.56 *F  Heat index: 17.96 *C 64.33 *F

So at this point, I know the problem is not with my program (happens with both my program and the DHTtest program), not with my Arduino (happens with both the 8266 in "the field" and my Uno on my couch). So something must be happening to the sensors in the field, where they work for a week to a few months, and then fail?

Any ideas?

I'm beginning to think some bug/critter is eating or doing something to the sensor (maybe they are attracted to it because it's warmer), but anyway is there a good way to shield if this is the case without affecting the values? Any other way to see what is going on?

 // Example testing sketch for various DHT humidity/temperature sensors
 // Written by ladyada, public domain

 #include "DHT.h"
 #define DHTPIN 2     // what pin we're connected to

 // Uncomment whatever type you're using!
 //#define DHTTYPE DHT11   // DHT 11
 #define DHTTYPE DHT22   // DHT 22  (AM2302)
 //#define DHTTYPE DHT21   // DHT 21 (AM2301)

 // Connect pin 1 (on the left) of the sensor to +5V
 // NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
 // to 3.3V instead of 5V!
 // Connect pin 2 of the sensor to whatever your DHTPIN is
 // Connect pin 4 (on the right) of the sensor to GROUND
 // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

 // Initialize DHT sensor.
 DHT dht(DHTPIN, DHTTYPE);

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

 void loop() {
     // Wait a few seconds between measurements.
     delay(2000);
     // Reading temperature or humidity takes about 250 milliseconds!
     // Sensor readings may also be up to 2 seconds 'old'
     float h = dht.readHumidity();
     // Read temperature as Celsius (the default)
     float t = dht.readTemperature();
     // Read temperature as Fahrenheit (isFahrenheit = true)
     float f = dht.readTemperature(true);

     // Check if any reads failed and exit early (to try again).
     if (isnan(h) || isnan(t) || isnan(f)) {
         Serial.println("Failed to read from DHT sensor!");
         return;
     }

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

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

This is how it looks when they fail.

The DHTxx are very low cost sensors, optimised for cheap volume production.

We don't know under what condition you actually use your sensors. Also, there's the phenomenon of knock-offs and low-grade selling.

In his comprehensive test, Robert J. Smith found a failure rate of 33% and concludes a mean life expectancy of one to two years.

A slightly more expensive alternative is the SHT series of temperature and humidity sensors. My personal experience is that they tend to tolerate some abuse (i.e. complete submersion in water) and don't age as quickly.

Link:

failure analysis: http://www.kandrsmith.org/RJS/Misc/Hygrometers/dht22_first_failure.html
general writeup: http://www.kandrsmith.org/RJS/Misc/Hygrometers/calib_dht22_dht11_sht71.html#conclusions


Where can i get touch sensitive buttons with RGB-LED like in Ableton Push I am searching for this component: a touch sensitive button with LEDs like in the Ableton Push or in other Launchpads. Does anyone have an idea about where I can buy something like this? The best would be an RGB LED.

This is what I've found so far. It has no RGB LED though.

Thanks!

Just a little more searching would have led you to this, along with its associated breakout board, bezels, and LEDs.


Flash "sketch" hex over ISP, without bootloader - possible? I'm wondering if it's possible to flash the arduino sketch into a AVR, without using a bootloader - over ISP. I'd use the BSD programmer, which is basically parallel port with some resistors.

Let's say I use the Arduino IDE, try to upload with "verbose" (no actual arduino is attached) - it shows path to the hex in the verbose output, and I "steal" the file.

Now I'd flash it using avrdude onto a blank 328 via ISP - would that work?

I assume there needs to be a 16Mhz crystal, is that it? Any other pitfalls I have to be careful about?

You don't need the arduino bootloader on the chip, if you are programming it using ISP.

It looks like BSD is no longer supported by avrdude.

In the Arduino 1.5 IDE you can add programmers, so you can do the uploading right from the IDE, instead of 'stealing' the hex file and manually uploading from the command line.

If the chips are blank you probably need to change the fuses first.

You don't need a 16mhz crystal. The atmega328 has an internal 8mHz oscillator inside.


Diagnosing crashed Arduino Uno I have an Arduino Uno connected to a motor controller over I2C. The Arduino accepts commands from a Raspberry Pi via the USB serial line.

I'm trying to diagnose a problem where the Arduino will become completely unresponsive. It's programmed to respond to a "ping" request every N seconds, and for some reason I can't identify, it seems to crash and no longer respond to any commands. However, the motor controller continues powering the motors.

Everything is powered from a 12V Li-Po battery, but everything is located behind 5V regulators. When this problem happens, the battery is fully charged and the motors aren't sourcing much current, and neither the motor controller or Raspberry Pi are effected, so I've ruled out a brownout.

My theory is there's some subtle programming error in my Arduino code that's causing an "exception", but I don't know how to identify it. I've tried adding special code to allow me to trigger one of these, by indexing an array outside of its limits or calling a null function pointer, but the Arduino stubbornly refuses to crash when I try to explicitly make it.

How do I diagnose an Arduino becoming unresponsive?

Assuming you don't have access to a debugger, the most common way is to add debug logging. The ususal algorithm to solve those problems is more or less like this:

do {
    add_logs_in_suspicious_places();
    wait_until_it_crashes();
    analyze_logs();
} while( ! i_know_why_it_crashes() );

If you cannot add any debug logging because of a flawed system design (lack of I/O, etc) you've commited a captial engineering crime and this is your punishment. :)


Ardutester Millenium I2c Lcd Not Showing Anything! Hiii Friends....,
I am Trying to Build Components tester Using Arduino Specifically Atmega328p Chip .
I Downloaded The Ardutester Millenium Code From Here ..  https://create.arduino.cc/projecthub/plouc68000/ardutester-millenium-the-ultimate-uno-mega-versions-c81db4
Edited Makefile.h By Enabling i2c lcd Interface And Adding My I2c Lcd Adress ...   But it wont work
I tried On Uno And Mega Also Serial Monitor Output seems ok But It Doesnt Display anything on 16*2 lcd
Thanks ...... :)

Code is available at that page sir...
Thanks for your reply

The schematic you posted is not for I2C. You have a connection to the regular 2x16 LCD character display. For the I2C an SSD1306.


Library compilation error Need help for this Tutorial. I tried to compile the code, but I'm getting compiling error.

I tried to ask on that forum too but got no answer, the error is:

In file included from C:\Program Files (x86)\Arduino\libraries\SD\src/utility/SdFat.h:32:0,
Multiple libraries were found for "SD.h"from C:\Program Files (x86)\Arduino\libraries\SD\src/SD.h:20,
 Used: C:\Program from D:\FEMV3FKI7YLJVQQ\FEMV3FKI7YLJVQQ.ino:1:
 Not used: C:\Users\IBNUM
C:\Program Files (x86)\Arduino\libraries\SD\src/utility/BlockDriver.h:31:10: fatal error: FatLib/BaseBlockDriver.h: No such file or directory
Multiple libraries were found for "SPI.h"
 #include "FatLib/BaseBlockDriver.h"
 Used: C:\Program
          ^~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.

How can I fix this Arduino compile error?

I have the same problem since version 1.8.10.

With a good running sketch I don't get any message "Multiple libraries were found" (and no warnings also)

But with every small compiler error I get a whole list of "Multiple libraries were found"

My custom libraries are in a sketchbook location
D:\DATA BACKUPPED\Documenten Albert\Arduino\Sketchbook-and-user-libraries


Receiving garbled `char` array returned by a function I return a char[300] array from a function.  If I intialize a char* variable with it, the return is garbled, but not if I append it to a String.  What gives?

  const char* post2 =  uploadHourCsv(timeNow,pulseChangeHour) ;
  String postS2 = "";
  postS2 =  uploadHourCsv(timeNow,pulseChangeHour) ;
  //const char* post2 = { uploadHourCsv(timeNow,pulseChangeHour) };
  if( debug ) {
    Serial.print("received in loop() as : [");
    Serial.println(post2);
    Serial.print("String : [");
    Serial.println(postS2);
  }

...

char postStr[300] = "";
// populate array
if( debug ) {
  Serial.print("postStrCsv generated: ");
  Serial.println(postStr);
}
return postStr;

  postStrCsv generated: 00000003;3|  0.00;8|17.55;9|17.55;10|18.12;11|16.92;20|93817;22|93789;101|6;time|1559646000;

  received in loop() as : [000?⸮@⸮⸮?" ⸮⸮?17.55;9|17.58! @0⸮⸮⸮⸮G% @5~`⸮h⸮?⸮⸮

  String : [00000003;3|  0.00;8|17.55;9|17.55;10|18.12;11|16.92;20|93817;22|93789;101|6;time|1559646000;

It's because you're returning a pointer to a local variable.

You are only returning the address in memory where your char array is allocated. That allocation is on the stack and only exists for the lifetime of the function.  But you still have the address where that memory was allocated, and you're using it as if it's still allocated.

When you append it to a String room is allocated on the heap and the data is copied in. That heap allocation remains until the String object is destroyed, either by going out of scope or by you manually destroying it.

It's pure chance that the data is still available and intact at the point of copying.

In short:

You must never return a pointer to a locally allocated (non-static) array.

Things you can do that are correct:

Pass an array pointer to the function to be populated by the function
Return a pointer to a statically allocated local array
Return a String object (though I wouldn't recommend using String for anything)

My preferred method is the first, whereby you define an array in the outer scope, then pass that (and possibly the array length) to the function. The function then populates the array it has been passed.  This also has the advantage that the function can use the return value to indicate a status or other quantity.

For example:

void myFunc(char *buf, int len) {
    for (int i = 0; i < len - 1; i++) {
        buf[i] = 'A';
    }
    buf[len - 1] = 0;
}

char myBuf[20];
myFunc(myBuf, 20);
Serial.println(myBuf);

--> AAAAAAAAAAAAAAAAAAAA


Arduino Robot won't move I am building a robot for a school project. I use an Arduino Uno, 2 dc motor's and an Ultra Sonic range measurement module. I want the robot to be autonomous, he has to be able to move around on his own using the Ultra Sonic sensor. Important to mention is that I don't use a MotorShield to control my dc motors. This is my latest version of coding:

#include <Servo.h> //include Servo library
#include <AFMotor.h> //include DC motor Library
#define trigPin 12// define the pins of your sensor
#define echoPin 13
AF_DCMotor motor2(7); // set up motors.
AF_DCMotor motor1(6);

void setup() {
  Serial.begin(9600); // begin serial communitication
  Serial.println("Motor test!");
   pinMode(trigPin, OUTPUT);// set the trig pin to output (Send sound waves)
  pinMode(echoPin, INPUT);// set the echo pin to input (recieve sound waves)
  motor1.setSpeed(105); //set the speed of the motors, between 0-255
    motor2.setSpeed (105);
}

void loop() {

   long duration, distance; // start the scan
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2); // delays are required for a succesful sensor operation.
  digitalWrite(trigPin, HIGH);

  delayMicroseconds(10); //this delay is required as well!
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;// convert the distance to centimeters.
  if (distance < 25)/*if there's an obstacle 25 centimers, ahead, do the following: */ {
   Serial.println ("Close Obstacle detected!" );
Serial.println ("Obstacle Details:");
Serial.print ("Distance From Robot is " );
Serial.print ( distance);
Serial.print ( " CM!");// print out the distance in centimeters.

Serial.println (" The obstacle is declared a threat due to close distance. ");
Serial.println (" Turning !");
    motor1.run(FORWARD);  // Turn as long as there's an obstacle ahead.
      motor2.run (BACKWARD);

}
  else {
   Serial.println ("No obstacle detected. going forward");
   delay (15);
   motor1.run(FORWARD); //if there's no obstacle ahead, Go Forward!
    motor2.run(FORWARD);
  }

}

Now I added an ARDUINO MOTOR SHIELD REV3 to control my dc motors. Now the wheels are actually spinning, but after a few turns they stop. I think it is software related, but I am not 100% sure. Also I think I am connecting my motors correct to my motorshield, but don't adress them properly in my code.
And I don't have any clue how to solve this problem.
Can anybody help me with this?

I think your problem is that you connected the positive wire to the 5v pin when it said 5v and not 9v. Also, I am assuming the 6 double AA is in series creating 9v. The thing is, double AA has a lot of amps. I tested it with my multimeter and it has 7 Amps, way to much. What I would do it connect a 9v battery to the voltage in pin-Vin. That pin can take a 9v but not 7 Amps produced by your 6 AA in series. You have 2 dc motors you said.Each is running I am assuming for each of them I notice draw about 1 Amp. 9v will supply enough and be safe. Try connecting a 9v to the Vin pin. I don't think your issue is software related.


Cant connect to localhost I have a project um Visual Studio with a GET method:
http://localhost:4548/Arduino/request?id=12&user=username&pass=password
When I open it in my browser, it works fine
But I want http GET in my Arduino, using the WebClient exemple:

EDIT
I used solution number 1. of @Matt and it worked:
Get a full licensed copy of IIS.
And this is the code after all:

#include <SPI.h>
#include <Ethernet.h>

//Informacoes de endereco IP, gateway, mascara de rede
byte mac[] = { 0xA4, 0x28, 0x72, 0xCA, 0x55, 0x2F };
byte ip[] = { 192, 168, 1, 200 };
byte gateway[] = { 192, 168, 1, 1 };
byte subnet[] = { 255, 255, 255, 0 };
byte server[] = { 192, 168, 1, 100 };

EthernetClient client;

void setup() {

  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /myProject/request?id=12&user=username&pass=password HTTP/1.1");
    client.println("Host: 192.168.1.100");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

My Serial displays as connected, but the http GET does not work
Am I missing something?

Visual Studio's web server is restricted to only servicing clients on the machine it is running on.
To do what you want to do there are a number of things you can do.

Get a full licensed copy of IIS. (Please stop laughing)
Get a version of Apache (might affect your server code and will take a while to setup)
Write yourself a 'proxy server'.  I think if you write a program to run on you PC that creates a socket that listens to port 8080 and forwards any messages on to the VS Web Server (use "C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\WebDev.WebServer40.EXE" /port:6666 /path:C:\WebServer\Root to start it on a fixed port) and forward any replies back to you client.


SMD Voltage Regulator 662k very hot, how to repair it? I think I made a mistake. Now, the 662k on my Arduino Uno very hot about 90°C.

I test it, it can be programmed and can run blink program normally.

There is a switch for voltage choose. Now, run in 3.3v mode get 2.8v and in 5v mode get 4.8v.

What should I do?

If 662k be replaced, can I use that Arduino normally in the future.

From the picture I guess it is a roboduino. The only voltage regulator is the 662k, it is too small compared to other voltage regulators!!! (have a look at the size and sink of the official arduino), so it is normal that the temperature is high. (arduino uno can get up to 1A and the regulator is bigger)

To reduce temperature just use the lowest input source (for instance, for arduino 5 volts, use 7 volts source, not 12 volts source). The bigger input voltage, the higher temperature in the regulator.

Solutions.

replace the 662K with another 662K one.
use a bigger voltage regulator. Since 66K space is tight (SOT-23) and no sink space I suggest to solder a TO-92 like voltage regulator. Not nice solution, but handy.


Simulate a FTDI using an Arduino UNO I'm looking to directly program an ESP8266 WiFi Module with out using a FTDI (USB-Serial interface) as suggested in this excelent tutorial. The real purpose is to have access to the GPIO ports of the module.

I heard (from this page) that one can use an Arduino UNO as an intermediate interface for burning the bootloader onto an AVR (e.g. ATmega168 or ATmega328). That is, using the ArduinoISP code example in the IDE.

Is it possible to use an Arduino UNO as temporal bridge to program the ESP8266? Can anyone please suggest some tutorial? Thanks

The simplest way is to unplug the ATMega328P from the board (or otherwise disable it) and just use the ATMega16U2 by connecting the ESP8266 to pins 0 and 1 of the Uno.  No programming required at all then - the ESP8266 just takes the place of the ATMega328P.

If you really want to "pass it through" the ATMega328P then you will need to make a transparent pipe for the serial data.  That would involve nominating two more pins on the Uno to be a new serial connection, and using SoftwareSerial to interface with those pins.  Then you have a simple loop which reads from one port and writes to the other, and the same in reverse of course.  Make sure you have the baud rates right.  I don't know how well SoftwareSerial would perform at the (commonly) 115200 baud the ESP8266 works at.

EDIT: (Interfacing to a 3.3-V system)

Since the ESP8266 works at 3.3V, while the ATMEGA16U2 is powered at 5V, you might need to adapt the level of the ATMEGA16U2's TXD line (which is connected to the "RX" input line of the ATMEGA328P/Arduino Uno Board), to 3.3V.

To do this, connect a  1.5 kOhm resistor between the RX pin and ground. In fact, the connection between ATMEGA16U2 and ATMEGA328P is done using an 1kOhm series resistor. This, together with the 1.5k Ohm resistor, will create a resistor divider, which converts the 5V output to 3V.

See schematics below.


SD test is taking long answer when it fails I am working on an Arduino application that logs sensors values into SD files. It is essential that the SD is inserted and working when a test is started, thus I need to check the presence of the SD regularly (every 2 seconds or so) to prevent launching a test without SD inserted by the user.

When I run the following code, it runs very fast when the SD test succeeds (<10ms), but it takes more than 2000ms when the test fails. Is there another test I could run that does not takes 2 seconds to indicate that the SD is not inserted (or not working)? All my buttons are frozen and they do not trigger any action while checking if no SD is inserted.

Here is my code (both loops have the same issue):

#define csSD   53
#include <SD.h>

Sd2Card card;

void setup() {
  Serial.begin(57600);
  bool SDOK = SD.begin(csSD);
  if(SDOK) {
    Serial.println("SD.Begin Setup OK");
  } else {
    Serial.println("SD.Begin Setup Fail");
  }
}

unsigned long t;
//void loop() {
//  t=millis();
//  if(SD.begin(csSD)){ // SD.Begin test runs fast when there is a SD, even though it return true when you try to begin SD a second time
//    Serial.print("SD.Begin loop OK : ");
//  }else {
//    Serial.print("SD.Begin loop Fail : ");
//  }
//  Serial.println(String(millis()-t)+"ms");
//  delay(500);
//}

void loop() {
  t=millis();
  if(card.init(SPI_HALF_SPEED, csSD)) {
    // card.init test returns true as it should (when SD is present and working), but runs fast only when SD is working
    Serial.print("card.init loop OK : ");
  } else {
    Serial.print("SD.Begin loop Fail : ");
  }
  Serial.println(String(millis()-t)+"ms");
  delay(500);
}

The SD library builds on the sdfatlib library, in which SD_INIT_TIMEOUT is defined as 2000 ms, which gives your 2 second timeout. You could try lowering that number to get a faster response, although that may run the risk of timing out even when a card is present.

Four different timeout periods are defined in the sdfatlib source:

/** init timeout ms */
uint16_t const SD_INIT_TIMEOUT = 2000;
/** erase timeout ms */
uint16_t const SD_ERASE_TIMEOUT = 10000;
/** read timeout ms */
uint16_t const SD_READ_TIMEOUT = 300;
/** write time out ms */
uint16_t const SD_WRITE_TIMEOUT = 600;

The 300 ms read timeout is faster, as @Paul suggests in his comment, so you could just use a card read as the test rather than an initialisation, or try setting the init timeout to 300 instead. A read test would be simpler, as it doesn't involve modifying library files. It might not cope with a re-inserted card, though - I suspect that requires reinitialisation each time.

Note: the version of sdfatlib included with the SDlib in my Arduino install appears rather older than the current version. The included version defines the timeouts in Sd2Card.h, while the latest has is in SdInfo.h. The snippet above is from the older, included code.


How to use arduino IDE to compile .s files Hi I'm new to arduino and im using it to learn assembly for my computer hardware 101 class, I read online that I can make the IDE accept .s files and compile them to the board but I dont know how to do this (something about editing the source code and recompiling the IDE?).

Could I get a step by step walk through? Assuming it's relatively simple, or just a link to some relevant documentation that's not a literal reference manual :-).

EDIT
As terrible as it is,I'm working from a macbook pro

The IDE should be able to accept .S files (not .s - the difference is very important: .S will be preprocessed, .s won't).

Just create a new sketch, and create a new tab called whatever.S (obviously rename the whatever to whatever you want to call it.

Then in the main sketch .ino file put something like:

extern "C" void myAssemblyMain();

void setup() {
    myAssemblyMain();
}
void loop() {
}

That will then call the function myAssemblyMain: in your assembly file and not much else.

(Note: I haven't tested this since I don't use the Arduino IDE).


Use TSL2561 and DS1307 RTC together I want to use a TSL2561 light sensor and a DS1307 RTC and a couple of other sensors like DS18B20, AS3935, ML8511, MQ135, 433 mhz sender together with an Arduino.
However on Adafruit I read this today (Quote from Adafruit)

  You may be wondering, how is it OK to connect a 3.3V chip like the
  TSL2561 to 5.0V data pins like the Arduino? Isn't that bad? Well, in
  this specific case its OK. I2c uses pullup lines to the 3.3V power
  pin, so the data is actually being sent at 3.3V. As long as all the
  sensors/device on the i2c bus are running on 3.3V power, we're fine.
  However, don't use a 5.0v powered i2c device (like the DS1307) with
  pullups at the same time as a 3.3V device like the TSL2561! If you
  want to use this sensor with a datalogger that uses the DS1307, remove
  any/all of the pullup resistors from the DS1307 SDA/SCL pins. The
  pullups built into the TSL2561 will then be active and keep the
  voltage at 3.3V which is safe for both the RTC and the sensor.

I don't really understand the meaning of this. What am I supposed to do? It tells me to remove the pullup lines on the RTC, but what are they and where can I find them? Are there any other sensors where I have to do this? If I don't remove the pullup lines, will I damage anything? Can someone clarify those things to me?

You can use the DS1307 itself just fine, but you are probably using a breakout board. These boards have (pull-up) resistors on it that will pull-up the I2C lines to 5v, while you only want 3.3v. This will not damage the arduino, but could damage chips like the  TSL2561, that can only handle 3.3v.

On the board you indicated you are using, you need to remove R2 and R3

Other 5v sensor breakout might also have pull-ups to 5v. Easiest way to check, is to connect 5v and ground, and then measure the voltage on the SDA and SCL pins. If it's 5v, then it has pull-up resistors that need to be removed.


Arduino Yun connection problems I followed this guide and evertything works until I'm at chapter Configuring the onboard WiFi.

I can see the arduino as an AP.

And I can connect with it. However when entering the IP adress 192.168.240.1 or arduino.local it does not give me the login page.
When using the IP adress I get: the site is not accessable screen. Using arduino.local gives me a page that loads forever for a long time before giving me the exact same result.

I have looked on different forums for a solution. This one said that I should download bonjour and bonjour browser because they use the same port (port 5353). After installing the bonjour browser I should be seeing a connection called .arduino._tcp but I don't see that. In fact I often can't see any connection what so ever.

and sometimes I can see a few connections but none of those are the arduino.

I have tried to ping with the arduino on the adress 192.168.240.1 but all I got was a time out.

Pinging 192.168.240.1 with 32 bytes of data:
Request timed out.

Edit : I managed to get the bonjour browser to work all the time, by installing itunes. It also shows the arduino.

You have to find IP address of your Yùn on your local network.
What I do in this case:
- look on the Home router if you can see your Yùn and it's ip, or,
- there is a sketch in Arduino Ide / exemple / bridge / wifi status which can help you to get ip, or
-  open the Arduino Ide software, upload serialTerminal sketch and open serial monitor. It allows you to access the Linux part of the Yùn and type 'ifconfig' to get the IP from the Yùn.


Serial Communication between 2 Arduinos for analogRead value I have an optical sensor connected to A0 on Arduino #1 (Nano) giving me values from 200 to 1010. I need to receive these values in Arduino #2 (Nano) through serial communication. I have used a simple code for sending and receiving bytes, but I don't understand how to get the actual sensor values as int. I found some examples showing single values, but as far as I can understand variable values are more complex.

Transmitter Code:

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

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
}

Receiver Code:

void setup() {
        Serial.begin(9600);
}
void loop() {
        if (Serial.available() > 0) {
        int incomingByte = Serial.read();
        Serial.print("I received: ");
        Serial.println(incomingByte, DEC);
        }
}

You'll want to get familiar with the standard C function sscanf().  It does exactly what you're looking for, converts an ASCII string into whatever type you like.

sscanf() API

The code to read an integer from the serial port would look something like this:

  char recv_buf[10];  int recv_int;
  Serial.readBytesUntil('\n', recv_buf, 9);
  recv_buf[9] = 0;  // make sure it's null terminated
  sscanf(recv_buf, "%d", &recv_int);
  Serial.print("I received: ");
  Serial.println(recv_int);


Adafruit nRF52 feather board [SOLVED] I am working on a project (the scenario is depicted in the attachment) involving Bluetooth Low Energy (BLE). As a master (central device) I am using the Adafruit nRF52 feather board (https://learn.adafruit.com/bluefruit-nrf52-feather-learning-guide/introduction) and as slaves (peripheral devices) a pair of Adafruit nRF8001 modules (https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/pinouts?view=all#introduction). Moreover, I have to wire the nRF52 up with an Arduino Uno rev3.

I am trying to set up the very initial communication between central and peripheral devices, but if I even try to upload the blinky sketch into the nRF52 board the compiling phase returns to me the following error:

  exec: "nrfutil": executable file not found in $PATH

Does anyone have an idea what it means? I googled a lot but I am not able to figure it out on this problem.

Thanks in advance to anyone would be able to help me!

Filippo

[EDIT] Solved: just need to install the nfrutil first, as written in https://learn.adafruit.com/bluefruit-nrf52-feather-learning-guide/arduino-bsp-setup#nrfutil-os-x-and-linux-only

Step 2 solves this problem:

https://learn.adafruit.com/bluefruit-nrf52-feather-learning-guide/arduino-bsp-setup

Also, read up about how to add something to Path Variable on Windows.