Arduino loading variables from an SD card Hello I have made a small game using and Arduino Uno and a Nokia 5110 screen. I use bitmaps to draw the images onto the screen. The problem is that bitmaps take up a lot of space and I can only use up to three bitmaps before running out of space. Is it possible to use an SD card to store the bitmaps on and have a method in the Arduino code to load a bitmap at a certain time, like when a button is pushed?

Yes, it is possible, but is it practical?

There's basically two ways of doing it:

Load the entire bitmap into RAM for displaying multiple times
Display the bitmap direct from the SD card.

As the Uno only has 2KiB of RAM that rather limits the size of bitmap that can be loaded into it. As you currently can have 3 bitmaps in flash (max 32KiB) I will assume they are considerably bigger than 2KiB each, so loading them into RAM is not really going to be doable on the Uno.

So the second option - drawing it direct from the SD card - is really the only practical way. The problem with that is reading from the SD card is considerably slower than reading from the internal Flash.  That means that your screen updates could be really slow, which would seriously impact the playability of your game.

All that happens when you draw a bitmap normally is that a loop iterates through the data and interprets each bit of each byte as a pixel being on or off and sets the relevant pixel to be on or off on the screen.  Instead of reading data from flash you just read bytes from the SD card and interpret them in exactly the same way.  If you take a look at the bitmap drawing routine in your LCD library you will see how simple it is - replacing the Flash access with SD card reading should be a simple enough matter to implement in your own copy of the routine.

A much better option would be to use a more powerful Arduino - one that has considerably more flash, such as the Mega2560.


Are there sensors that can detect the color of an LED? Are there sensors that can detect the color of an LED?

I am working on an Arduino project that needs to detect the color of an LED on an external device. I am trying to identify a light sensor that can be connected to the Arduino's input that can tell me the color of light the LED is currently emitting. The LED is capable of displaying red, green and yellow.

You can use an LED as a light sensor - http://www.instructables.com/id/LEDs-as-light-sensors/

In theory, LEDs should be most sensitive to the frequency it emits - if this is true, the same type of red/green/yellow LED would be best.

I don't know how sensitive this will be.

If you control the "external device", then you could get much better accuracy by blinking the LED at very high rates (not visible to the human eye). Or, if you can get at the legs of the LED, you can tap into the signal directly (you should use an opto-isolator - even if powered at a few volts, the ground of your project may be different from the ground of the external device, causing 100s of volts to run through your Arduino - not good!).


How to add prefactor to clock frequency at compile time? I want to use an Arduino Mega at 8MHz because my power supply is bad and I have only 4.3V (no way I can fix that), which is outside the operation range of the ATMega1280 at 16MHz. I think the right way to do it is to put a pre-factor 2 on CLKPR (tell me if I am wrong)? I know that several pages explain how to do so in a sketch: see How can you reduce the clock frequency of an Arduino Mega? , https://playground.arduino.cc/Code/Prescaler .

However, both those methods reduce the Mega frequency at run time, by setting the CLKPR register during the setup loop or another function, mess up with the millis(), delay(), Serial etc, and in addition I guess this means that the Mega is running at an out-of-spec 16MHz until the prefactor is set in the setup loop (?). So my question (I searched for it but found no answer) is:

Can one set the clock prefactor at compile time, so that:

the compiler knows about it,
the millis(), delay(), Serial and similar are not disturbed
the register is set immediately at boot (i.e. no need to change the registers in the setup)

?

1 and 3 can be solved by putting it in one of the initialization sections. 2 can be solved by creating and using a board.txt entry with the appropriate FCPU.

#include <avr/power.h>

void __attribute__((naked, section(".init1"))) preprescale(void)
{
  clock_prescale_set(clock_div_2);
}


Did I accidentally short something? My Arduino UNO board does not communicate with the computer anymore I had my sketch uplaoded and everything was working fine when I tried connecting one of the input pins(pre-configured as digital INPUT) to 12V, just to see if this was being read as a HIGH as well.
It seems to have done something and the board stopped working. Moreover, all pins seem to be stuck at HIGH!

So far Ive tried the following:

reset button: doesnt help
re-upload: doesn't work - it says not in sync

Physically nothing seems to be burnt/blown. What am I missing? Have I fried my board? I hope not. PS: It was connected to a 12V external power source

Any thoughts?

Unfortunately, the arduino's input pins are not tolerant of 12 volts, You have likely caused permanent damage to the chip =(. There is a regulator that makes it capable of being powered by 12 volts, but the input pins are different.

If you look at table 30-1 on the datasheet for the Uno's controller here you can see the input characteristics. The arduino is powered at 5v, so the max digital input voltage is 5.5v


LED on same Pin as Toggle Switch, not illuminating I am trying to do something I think should be relatively simple. I would like to read an input from a toggle switch, and have a red 5mm LED indicate the state of the switch. Rather, however, than have an input for the switch and an output for the LED (controlled by software), I'd like to put them in series on a single circuit. That is, flip the toggle and current flows from the 5v source on the Arduino Uno through an LED and to an input pin on the Arduino. (I would ultimately like to have eight such switches; I am trying to create a sort of simulated byte, with individually flippable bits controlled by toggles; this will be read by a GTK Python program, that can interpret that "byte" in different ways: as a decimal value, a hex value, an ASCII character, a color in 8-bit color space, etc).

So, I have an LED with a 200 Ohm current-limiting resistor. I also have a pull-down resistor (1k) to prevent the toggle from floating.

My results, however, have been inconsistent. Using a breadboard, I've gotten this working. But it seems very fragile, and sometimes when I rebuild the circuit on a breadboard, it doesn't work as expected. Right now, for instance, the switch seems to work, and I am reading the expected value from the Serial Monitor--but the LED is not illuminating.

I had been playing around with different values for the pull-down resistor and the current-limiting resistor. This pair (200-ohm current limiting; 1k pull down) seemed to work, but now isn't. (I have swapped out the LED; and current is passing through the LED, otherwise I wouldn't be able to read the correct pin value--I think.)

Is there something I'm not understanding? Does the position of the current limiting resistor (before/after the LED) make any difference (I assume not)? Does this seem like the correct setup for what I'm trying to achieve? More generally, should, in principle, this approach scale to 8 more toggle/LED pairs? Is there a better/smarter approach? Is there a reason why I see so few Arduino projects that put LEDs in series with an input toggle?

The breadboard looks like this:

LEDs have a (fairly) fixed voltage drop across them.  The red LED is about 2V.

You can use that to work out the voltage at the input.  You basically have a voltage divider, with your 200Ω resistor as R1, and your 1kΩ resistor as R2.  The voltage drop of the diode is subtracted from Vin.

So:

Vout = (Vin - Vled) * (R2 / (R1 + R2))

     = (5 - 2) * (1000 / (200 + 1000))

     = 3 * (1000 / 1200)

     = 3 * 0.833

     = 2.5V

The ATMega328P datasheet states that a HIGH input voltage must be over 0.6*Vcc, and a LOW input voltage must be below 0.3*Vcc.  That means to register a HIGH you need more than 3V.  To register a LOW you need less than 1.5V.

You're between those two voltages - in the "dead zone".

The simplest way to achieve what you want is to use a douple-pole switch and keep the LED completely separate from the Arduino.


Teensy 3.1 no overclock option for 168 MHz I'm sorry if this isn't the right area. Teensy uses the arduino ide.

I've seen some people show off the 144 mhz and 168 mhz option in their ide. I read in the Teensyduino 1.19 release notes that the options were added but not enabled. I would like to know how to enable it or if I somehow downloaded an older version.

P.S I get the 96 mhz option.

Thanks ahead of time!

Using the latest Teensyduino distribution as of this writing, 1.25, you have to uncomment the higher overclocking options in the boards.txt file, located here in my install-
/hardware/teensy/avr/boards.txt

The options look like this, just remove the # symbol-

#uncomment these if you want to try faster overclocking
#teensy31.menu.speed.168opt=168 MHz optimized (overclock)
#teensy31.menu.speed.144opt=144 MHz optimized (overclock)
#teensy31.menu.speed.120opt=120 MHz optimized (overclock)`


MD5 hash for Arduino Uno [-Wshift-count-overflow]? I tried to test out this MD5 library (https://github.com/tzikis/ArduinoMD5 ) as a hash function on arduino uno.

What I have done is that I placed the MD5.cpp and MD5.h to the folder below:
C:\Program Files (x86)\Arduino\libraries\MD5

And launched arduino IDE 1.8.9 to test the example provided (https://github.com/tzikis/ArduinoMD5/blob/master/examples/MD5_Hash/MD5_Hash.ino):

#include <MD5.h>
/*
This is en example of how to use my MD5 library. It provides two
easy-to-use methods, one for generating the MD5 hash, and the second
one to generate the hex encoding of the hash, which is frequently used.
*/
void setup()
{
  //initialize serial
  Serial.begin(9600);
  //give it a second
  delay(1000);
  //generate the MD5 hash for our string
  unsigned char* hash=MD5::make_hash("hello world");
  //generate the digest (hex encoding) of our hash
  char *md5str = MD5::make_digest(hash, 16);
  free(hash);
  //print it on our serial monitor
  Serial.println(md5str);
  //Give the Memory back to the System if you run the md5 Hash generation in a loop
  free(md5str);
}

void loop()
{
}

However when run verify and compile, it works but got the warnings below:

...\sketch_may02a_MD5_test.ino.ino: In function 'void setup()':

sketch_may02a_MD5_test.ino.ino:15:51:
warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

   unsigned char* hash=MD5::make_hash("hello world");

                                                   ^

C:\Program Files (x86)\Arduino\libraries\MD5\MD5.cpp:
In static member function 'static void MD5::MD5Update(void*, const void*, size_t)':

C:\Program Files (x86)\Arduino\libraries\MD5\MD5.cpp:207:21:
warning: right shift count >= width of type [-Wshift-count-overflow]

  ctx->hi += size >> 29;

                     ^

I know little of c++, can anyone help to fix this? Thanks a lot!!

....\sketch_may02a_MD5_test.ino\sketch_may02a_MD5_test.ino.ino:15:51: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

That is a flaw in the library. The author defined the function as taking a char * instead of a const char *.  You can ignore it, it's just a warning - however maybe raising the issue with the author could be a good idea.

  C:\Program Files (x86)\Arduino\libraries\MD5\MD5.cpp:207:21: warning: right shift count >= width of type [-Wshift-count-overflow]

This one is a little more awkward.  The size variable is defined as type size_t.  That varies in length depending on the architecture the software is compiled on.  On the 8-bit Arduinos that's a 16 bit variable. On 32-bit Arduinos, like the Due, it's a 32-bit variable.

It is probable that the author developed the library using a 32-bit Arudino (or Arduino-compatible) device - in which case he would never see that warning (since 29 is less than 32).  However anyone that then uses an 8-bit Arduino gets the warning, and probably a corrupt hash.

However, it looks like it should only be a problem if size is too big - and it can't be on an 8-bit Arduino. So again you can ignore it, but the author should really be made aware of the issue.


DC motor phototransistor control So basically I have a circuit with a phototransistor, and want to convert the phototransistor value into a PWM signal that can control the speed of the motor. The code I came up with is below, however it does not work. What have I done wrong in my code? I am using an l293d chip.

int photoTran = A1;
int reading = 0;
int forward=2;
int backward=3;
int motorspeed=0;

void setup(){
  pinMode(photoTran,INPUT);
  Serial.begin(9600);
  pinMode (backward, OUTPUT);
  pinMode (forward, OUTPUT);
}

void loop(){
  lcd.setCursor(0,0);
  reading = analogRead(photoTran);
  lcd.print(reading);
  lcd.print("  ");
  delay(100);
{
  if (reading<30){
    digitalWrite(backward,HIGH);
    digitalWrite(forward,LOW);
    motorspeed = map(reading, 30, 1023, 0, 255);
    analogWrite(backward,motorspeed);
  }
  else {
    digitalWrite(backward,LOW);
    digitalWrite(forward,HIGH);
    motorspeed = map(reading, 30, 400, 0, 255);
    analogWrite(forward,motorspeed);
  }
  }
}

analogRead() returns an integer between 0 and 1023. Using 30 and 400 in the map() function, then passing in a value outside of that range will cause strange results. Here is a sketch to illustrate my point.

void setup(){

  Serial.begin(9600);

  // Prints -20 to 684
  for(int i = 0; i < 1024; i++){
    Serial.println(map(i, 30, 400, 0, 255));
  }
  Serial.println();

  // Prints -7 to 255
  for(int i = 0; i < 1024; i++){
    Serial.println(map(i, 30, 1023, 0, 255));
  }
  Serial.println();

  // Prints 0 to 255
  for(int i = 0; i < 1024; i++){
    Serial.println(map(i, 0, 1023, 0, 255));
  }
}

void loop(){}


Can't use enum as function argument I declared my enum and called it Dir. I wanted to use value of that type in my function Move(). Here's the code:

enum Dir
{
  forward = 1,
  backward = 2,
  left = 3,
  right = 4
};

void Move ( Dir direction , int distance )
{
     direction = forward;
}

void setup() {
  // put your setup code here, to run once:

}

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

}

Unfortunately i get the following errors:

V2.ino:23:13: error: variable or field 'Move' declared void
V2.ino:23:13: error: 'Dir' was not declared in this scope
V2.ino:23:29: error: expected primary-expression before 'int'

What's wrong?

I did not experience the problem because I usually use a Makefile instead of
the Arduino IDE. I now tried with the IDE version 1.0.5 and I had the same
problem as you. The fix is to explicitly declare the function before
defining it:

void Move(Dir direction, int distance);
void Move(Dir direction, int distance)
{
     direction = forward;
}


Is there an easy way to turn integer values to pixels? I'm working with a black & white camera and it gives me integer values to represent the amount of light hitting the sensor. Very bright is 1023 and totally dark is 0. The values are printed through serial and everything works fine but now I want to recreate the image based on the values.

Does anyone know if there is a simple way of doing this? I'm assuming the process would consist of looking up the value and giving a specific colored pixel in return, but I have no idea how to do this.

Simplest thing may be to write down your image in plain Portable Gray
Map format. This is a very
simple (and inefficient) ASCII format consisting of a signature (the
string "P2"), followed by the width and height of the image, followed by
the maximum possible gray level (1023 in your case), followed by the
pixel values. It's a free form format, meaning you can mix spaces and
newlines at your convenience.

Here is an example image: two rows of pixels, five columns, and
brightness increasing left to right and top to bottom:

P2
5 2
1023
  0 111 222 333 444
555 666 777 888 999

Then, any image conversion software should be able to convert that into
the format of your choice (PNG, JPEG, whatever...).


Is there a way to go to the start of the void loop() function kind of like a "continue" keyword in c in loops? I am new to Arduino programming and am trying to make an obstacle avoiding car with an ultrasonic sensor and a differential driver model. While learning how to code it, I learned that you can exit the void loop() function with an exit(0) to terminate the program analogous to break keyword in C language.
Is there anything similar that I can use to mimic the "continue" keyword, say if I don't want to run the code after a particular line in the void loop() function.

In the loop() function, return will perform that function. By exiting the function, the for() loop in main() (which we don't see) will iterate again, calling loop() again.
Another way to accomplish the same thing is to write everything in your setup() function, including whatever kind of loop construct you want, and use break; and continue; statements as you're used to:
void setup(){
   // pinMode() & digitalWrite() calls
   // Initialize the Serial port if you need to
   // Any other one-time setup
   //
   // Everything happens here:
   for( .... ){
      // loop contents here
      if( whatever ){
         continue;
      }
      else if( something_else ){
         break;
      }
   }
}

// This just stalls forever when setup() ends:
void loop(){
   ;
}


How to get separate BPM readings from two pulse sensors using one Arduino Here is the code I used to get BPM from pulse sensor.

#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most
acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground
Library.

//  Variables

const int PULSE_SENSOR_COUNT = 2;
const int PulseWire = A0;
const int PulseWire2 = A1;
const int LED13 = 13;
int Threshold = 550;

void setup() {
  Serial.begin(9600);
  pulseSensor.analogInput(PulseWire, 0);
  pulseSensor.analogInput(PulseWire2, 1);
  pulseSensor.blinkOnPulse(LED13);
  pulseSensor.setThreshold(Threshold);
  if (pulseSensor.begin()) {
  }

  void loop() {
    int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".

    if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".
      //Serial.println("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
      Serial.print("BPM1: ");                        // Print phrase "BPM: "
      Serial.println(myBPM);                        // Print the value inside of myBPM.
    }
    delay(20);                    // considered best practice in a simple sketch.
  }

I wish to separate display the BPM that get from A0 wire and A1 wire. Serial could print something like this: BPM1(A0):75, BPM2(A1):80.
I don't know how to do that, can anyone help me with it?

Change "#define USE_ARDUINO_INTERRUPTS true" to "#define USE_ARDUINO_INTERRUPTS false".

If, instead, your Sketch does not use interrupts to read PulseSensor data, your Sketch must instead contain the following two lines, in order:
#define USE_ARDUINO_INTERRUPTS false
#include <PulseSensorPlayground.h>

Source: https://github.com/WorldFamousElectronics/PulseSensorPlayground/blob/master/src/PulseSensorPlayground.h


What is the proper way to turn an Arduino UNO into an ISP? I have a bricked Arduino Uno and I want to try to flash the bootloader. I'm trying to figure out how to do it. On this tutorial from SparkFun you can see this diagram:

They also show this table of the pinout

That seems simple enough but it's totally different than the official tutorial, "Circuit (targeting Arduino Uno, Duemilanove, or Diecimila)"

Which also says

  An Arduino board serving as an ISP to program the ATmega on another Arduino board. On the Arduino Uno, you'll need to connect a 10 uF capacitor between reset and ground (after uploading the ArduinoISP sketch). Note that you need access to the reset pin on the target board, which isn't available on NG or older boards.

So do I need a 10 uF capacitor between reset and ground? How do I put a 10 uF capacitor in between reset and ground when, in this configuration, reset is connected to PIN 10? Why are there two configurations? What's the upsides and downsides to either of them?

The wiring is actually identical. It just uses the ISP header (2x3 pins) on the target board, instead of the pins 5v, GND, RST, 11, 12, 13. Just like the table you added says.

The downside to using the ISP header, is you need a male to female wire for connecting. Upside is you can easily take of these 6 pins, and connect it to a different arduino to be programmed.

I always needed to add a capacitor between RESET and GND. The exact value isn't that critical.

The reset pin is the one to the left of 3v3.


Stepper Motor Button Press I am having difficulties programming what should be a simple sketch that gets my stepper motor to run at one step per second indefinitely at the press of a button and then stops at the press of another button. I am using the Bounce2.h and accelstepper.h libraries and have been unable to figure out how to do it. Any help would be greatly appreciated, and as for hardware I am using a NEMA 23 High Torque Stepper Motor connected through a M542T Motor Driver powered by a Switching Power Supply and running on an Arduino UNO.

Attatched find my code, and thank you so much for the help!

#include <Bounce2.h>
#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
#include <AccelStepper.h>

AccelStepper stepper(1, 9, 8); // initiate stepper motor

//int buttonPresses = 0;
const byte ButtonPin = 10;
const byte LedPin = 13; // for debugging and visualization

Bounce button;

void setup() {
  Serial.begin(9600);
  button.attach(ButtonPin);
  pinMode(LedPin, OUTPUT);
  stepper.setSpeed(1);
}

void loop() {
  if (button.rose()) {
    stepper.runSpeed();
    digitalWrite(LedPin, HIGH);
    //    buttonPresses++; // count presses of button and print to monitor
    //    Serial.print("Number of Button ");
    //    Serial.print("Presses = ");
    //    Serial.println(buttonPresses);
  }
  else {
    button.update();
    digitalWrite(LedPin, LOW);
    if (button.fell()) {
      stepper.stop();
    }
  }
}

As of now, a button press runs the motor at 1 step/second, but a second press or any subsequent presses thereafter do nothing to stop the motor. Thanks so much!

!!EDIT!!

Upon adding a boolean buttonState and setting it to LOW in the setup and changing my void loop() code to look like:

void loop() {
  button.update();
  if (button.rose() == true && buttonState == LOW) {
    stepper.runSpeed();
    digitalWrite(LedPin, HIGH);
    buttonState = HIGH;
  }
  else {
    if (button.fell() == true && buttonState == HIGH) {
      stepper.stop();
      buttonState = LOW;
    }
  }
}

I know get a step every button press. Just thought it may help in answering.

EDIT 2

So I I tried pulling the runSpeed() out of the loop and adding                                                            if (buttonState = HIGH){stepper.runSpeed();}
but that now just runs the stepperMotor constantly and at variable speed and will not turn it off?

EDIT 3 and Working Code
Thank you Janw for the help. I realized my fault in calling the runSpeed function within the if statement. Further, I also needed to change button.fell() to button.rose() since button.fell() returns true when the button is released, so basically I was stopping the motor everytime I let go of the button. Here is the final, and working void loop() in case anyone runs into a similar problem in the future:

void loop() {
  button.update();
  if (button.rose() == true && buttonState == LOW) {
    digitalWrite(LedPin, HIGH);
    buttonState = HIGH;
  }
  else {
    if (button.rose() == true && buttonState == HIGH) {
      stepper.stop();
      buttonState = LOW;
    }
  }
  if (buttonState == HIGH) {
    stepper.setSpeed(1);
    stepper.runSpeed();
  }
}

You will probably get only 1 step each button press because your runSpeed() is within the if (button.rose() == true && buttonState == LOW)-statement.

The runSpeed() needs to be called every loop to check if the motor needs to step.

A simple way to change this is to set a boolean to true or false if you check your button and add something like this pseudocode:

if(motorRun == true) stepper.runSpeed();


Purpose of LED indicator I am using an arduino mega clone called the Funduino.
I am developing a python based, tkinter application that will receive the serial data that arduino sends.
However, i am witnessing some behavior that i cannot explain and i am trying to debug. I won't say anything more, because this is an arduino forum, not a python forum.
But, in the arduino, there are some leds. One of them is power, which is constantly ON, when the arduino is powered.
There is another led that is named 'L'. When i open a serial connection this is lighted up and it stays ON.
However sometimes, when i send a string to the arduino, in order to trigger some data exchange, this button is switched off.
So what does this 'L' led is, and what it means when it is turned off?

This buildin LED is connected to an IO pin of the microcontroller on the Mega (most commonly pin 13, but might be different depending on the board). So the meaning depends on what the code on the Mega does with it.
When the board is reset (which happens on opening of serial connection), first the bootloader will run. It gives you a short blink on the buildin LED. After the bootloader finishes, your own code is in charge. Whatever you do in your code with pin 13 will be reflected on the LED. Here the meaning depends on you.


Simple compiler design help: Variable length arrays? I'm trying to write a simple compiler in C++ for a language that I am making up for my lab.  The compiler will have to be able to turn a string like this:

"do command_one 3 times"

into a data structure that represents this:

<command_one>, <command_one>, <command_one>

it should also be able to turn something more complicated like this:

"do do c_one do c_two 2 times 2 times c_thr 2 times"

into a data structure that represents this:

<c_one> <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr> <c_one>
                <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr>

Another function will then read the commands out one by one.

These examples show all of the functionality that I would want from the compiler.

I'm having design issues for the compiler that I want to create.  Initially, I just wanted to do some string manipulation and turn the input string into an array of integers representing commands.  However, since the compiler will be outputting an arbitrarily large number of commands, and since arrays in C++ need to be initialized with a length, this could be a problem.

I am not fluent in C++ so I am hoping that a C++ whiz can show me a quick solution.  I have already come up with the suggested solution on my own in Python, however, my solution in Python has to do with the ability to change the length of lists on the fly.

EDIT: I am also intending to use this code for an Arduino, which supports C++ code but not the standard libraries.  I found the vector solution to work in my C++ code, but it will not work in the Arduino interface.  Is there a way to do the compiling WITHOUT using vectors?

In C++ there is a std library container called vector you can use to create variable length arrays. You can use it like this:

#include <vector>
// ...
std::vector<int> commands;
// ...
// parse string and generate commands, add your commands with push_back
commands.push_back(new_command);
// and you can access elements in the array like normal
commands[0];
// and also see how many elements are in the array
commands.size();

I also want to mention the std stack, which I think would be a helpful class for managing the states of your nested loops. Each time your interpreter enters a new loop for example, push to the top of the stack how many times to run, and each iteration count down till 0 and pop (just as an example).

Edit:
Because you can't use vectors C++ also supplies the new and delete keywords to dynamically allocate and delete memory. However as arduino has really low memory I don't recommend trying to implement an expansible array on this.
This post here mentions that program memory and global memory is shared on 2K: new operator on arduino

You may just want to go with a reasonably sized static array on arduino considering the memory limitations. I would suggest using a pool or the new + delete stuff but any implementation you add to deal with memory management will take away space you need for your interpreter and its instructions.

Also I don't know what data type you've chosen to represent your instructions but char is probably best  on the embedded implementation if your instruction set is small as it only occupies one byte each.


How can I control the speed and direction of dc motor at the same time (through Bluetooth I am working on a project of an arduino car it's simple really i know how to control the speed and direction using simple button but I was looking for an upgrade so I add a virtual joystick in my app now It can send 2 values first is the angle where the pointer of the joystick is which will be used to control the direction. And the distance between the center of the joystick and the pointer will be used to control the speed, problem is they are both int values how can I make the arduino differentiate between both values ? also they would be sent simultaneously over Bluetooth which might be a problem as well

Use delimiters to separate the two values you are sending over bluetooth.

Something like

"30,5\n"

instead of

"30\n"
"5\n"

On the Arduino side, read the the incoming string into a char array and add a \0 after the last read character to make it a C string. The use strtok() to parse the C string and atoi() or atof() to convert the parsed C strings to an int or float.

See this answer for more information about parsing a string.


Sending serial data to Arduino from Matlab(not using support package) I am learning Arduino and trying to understand how integers and strings are sent across the serial port.
I tried a small program in arduino which reads a number as a string and tries to blink led 13 according to that number. Below is the arduino side of code.

const int ledpin = 13;
int value = 0;
int blinkrate;
void setup()
{
   Serial.begin(9600);
   pinMode(ledpin,OUTPUT);

}

void loop()
{
    if (Serial.available())
      {
         char ch = Serial.read();
         if (isDigit(ch))
            {
               value = (value*10) + (ch - '0');
            }
         else if (ch == 10)
            {
               blinkrate = value;
               Serial.println(blinkrate);
               value = 0;
            }
      }
    blinkled(blinkrate);
}

void blinkled(int blinkrate)
 {
   digitalWrite(ledpin,HIGH);
   delay(blinkrate);
   digitalWrite(ledpin,LOW);
   delay(blinkrate);
 }

When i try to send a string from MATLAB, the RX led blinks once indicating something is coming, but the LED on pin 13 is not behaving accordingly(it should blink according to the number i send). Here is the matlab side of code.

pre_open = instrfindall;
delete(pre_open);
serial_port = serial('COM3');
set(serial_port,'Terminator','CR');
set(serial_port,'BaudRate',9600);
set(serial_port,'DataBits',8);
set(serial_port,'StopBits',1);
set(serial_port,'Parity','none');
fopen(serial_port);
num = 200;
fwrite(serial_port,int2str(num));
data = fscanf(serial_port,'%d');
pause(2);
fclose(serial_port);

When i try to read the return string from arduino, MATLAB shows me a timeout error.

I would be grateful if anybody points me to the right solution.
Thank you.

Got it, instead of depending on the Serial object, i sent the line feed to arduino. All this time it has been waiting for the Line feed that never arrived.

delete(instrfindall)
s = serial('COM3', 'BaudRate', 9600); %38400
fopen(s);
pause(0.1);
text = input('enter','s');
fprintf(s,'%s\n',text,'sync');
pause(0.1);
d = fscanf(s,'%s');
pause(0.1);
delete(instrfindall)


Arduino Uno + Jaguar Speed Controller + CIM Motor (12V DC) I have connected a CIM motor to a Jaguar speed controller, powered by a 12V battery. The Jaguar is connected to an Arduino Uno via the signal and ground. Also, I have two switches connected to the Arduino, for forward and reverse of the motor.

In the code, for speed of the motor, I have set 90 as the mid point and 100 for forward and 80 for reverse. When I push the reverse button, the motor runs smoothly in the reverse direction at the set speed. However, the problem is, when I press the forward button, the motor runs seemingly slower in the forward direction than the set speed.

My logic here was, if I have set speeds in forward and reverse at +/- 10 from the mid-point, the motor should run at the same speed in the forward and reverse direction, but this is not happening.

I am pasting my code below. Any help would be much appreciated. Thank you!

#include <Servo.h>

int forwardPin = 2;
int reversePin = 4;
int motorPin = 10;
int fwdReading = 0;
int revReading = 0;

Servo myservo;

void setup() {
  TCCR1B = TCCR1B & 0b11111000 | 0x04; // PWM Freq. at 122Hz
  pinMode (forwardPin, INPUT);
  pinMode (reversePin, INPUT);
  myservo.attach(motorPin);
  myservo.write(90);  // set servo to mid-point
}

void loop() {
  fwdReading = digitalRead(forwardPin);
  revReading = digitalRead(reversePin);
  if (fwdReading == HIGH) {
    myservo.write(100); // forward
  } else if (revReading == HIGH) {
    myservo.write(80); // reverse
  } else
    myservo.write(90); // neutral
}

I searched for the library you're using and the arduino website mentions :

  0 being full-speed in one direction, 180 being full speed in the other, and a value near 90 being no movement

From this we can take that the value 90 is not perfectly in the middle of the speed range therefore 10 points under 90 won't necessarily be equivalent to 10 points above 90.
My only advice is to try and find the equivalence point yourself by trail and error.
Even though 90 seems to cause no movement, try 89 or 91 see if they also have the result and so on.

Or simply try different values to get same speeds in different directions, it's ok if you use different values (away from 90) for the two different directions :P.

Gd Luck


Value of joystick reduces when I send it over serial I've got two arduino cards and two bluetooth bluesmirfs. I am currently trying to read value from a joystick and send it over to the other arduino card and use that value to control my servo motor.

Here's my code.

       //Master Code
void loop()
{
    yVal = analogRead(yAxis);   (value between 0 and 1023)
  if(bluetooth.available())
  {

    bluetooth.print(yVal);
  }
  else if(Serial.available())
  {

    Serial.print(yVal);
  }
  delay(100);
}

//Slave code
void loop(){
  while(Serial.available())
  {

    int c = Serial.read();
    Serial.print("Joystick value: ");
    Serial.println(c);
    int val = map(c, 0, 1023, 0, 255);
    Serial.print("Map value: ");
    Serial.println(val);

      myServo.write(val);
    }
  }

Am I doing something wrong? Instead of getting something between 0 and 1023 I get something below 50.

A fundamental lack of understanding of how serial communications works is what you have.

Serial sends bytes. You are attempting to read an int. The two don't match. Not only that, but you are sending the value as text, not a number, so you're interpreting it as gibberish.

My suggestion: do the map on the master not the slave, and send a raw byte between 0 and 255 not a string of text between "0" and "1023".

bluetooth.write(map(yVal, 0, 1023, 0, 255));


A few questions on the first steps with an ESP32/ESP8266 NodeMCU I would like to know what are the first steps, as a good practice, when receiving a new ESP based NodeMCU. For example:

Checking if everything works fine
After you connect to the relevant COM port, using either putty, Arduino IDE or any other method, what are some basic commands to check the version and the status of hardware in general?

Reassuring a restore point
Is there a way to keep the initial/factory firmware in some kind of image? Or is the basic firmware stored in some kind of ROM that can't be changed by a user no matter what? In other words, is it possible to "brick" a NodeMCU in case something goes wrong, and how to prevent that?

Restore from backup
What is the proper reverse process to restore a NodeMCU to a previous state?

C / microPython
I have seen some projects using microPython instead of C, what is the standard way for start using a NodeMCU with microPython?

LUA (LUA shell)
What exactly is the role of LUA in a NodeMCU? Is it just the interface a user has available after the COM connection?

Checking if everything works fine

  After you connect to the relevant COM port, using either putty, Arduino IDE or any other method, what are some basic commands to check the version and the status of hardware in general?

Program it. If it behaves as you expect then it's working.

  Reassuring a restore point

  Is there a way to keep the initial/factory firmware in some kind of image? Or is the basic firmware stored in some kind of ROM that can't be changed by a user no matter what? In other words, is it possible to "brick" a NodeMCU in case something goes wrong, and how to prevent that?

Why would you want to? You can just download it. And "bricking" is hard, since you are programming the board afresh every time you hit "upload" in the Arduino IDE.

  Restore from backup

  What is the proper reverse process to restore a NodeMCU to a previous state?

You just upload whatever you had loaded on there before.

  C / microPython

  I have seen some projects using microPython instead of C, what is the standard way for start using a NodeMCU with microPython?

Install it, then interface with it, however that is done. We're Arduino here, so we support using the ESP8266 etc with the Arduino API. We don't support MicroPython.

  LUA (LUA shell)

  What exactly is the role of LUA in a NodeMCU? Is it just the interface a user has available after the COM connection?

It is another programming language. Like MicroPython. Use it if you like - however, it's a dying language and learning it is not recommended. Again, we don't support Lua.


problem with decrement in a loop I am trying to write a sketch wherein the led brightness increases in increments of 15 until it reaches 255. At that point I want to make decrements of 15 until it reaches 0. The increment part of the program works well but the decrement part goes haywire. It gets stuck between 255 & 240. I am not sure how can I fix it. Could you please tell how can I make it work?

Here is my sketch:

int led = 9; //led pin
int fade = 0; // pwm value

void setup() {
  // put your setup code here, to run once:

  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

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

   analogWrite(led,fade);
   fade += 15;
   Serial.println(fade);
   delay(250);

  if (fade >= 240){
    fade = fade - 15;
    analogWrite(led, fade);
    Serial.println(fade);
    delay(250);
  }

}

The problem is that you add 15, and than if it's >= 240, you decrease 15, so it will not change  (I wouldn't consider it haywire though).

You can better use a direction sign. Below is only the relevant code (not the GPIO functionality). What it does in the loop is, in case up is true, it adds fifteen, otherwise it subtracts 15. When 255 is reached, it starts counting down (up is false), when reaching 0, it starts counting up (up is true). This only works if 255 / the amount to add/subtracts reaches exactly 255, otherwise you have to check for <= 0 and >= 255.

bool up = true;
int fade = 0;

void loop()
{
    fade += up ? 15 : -15;
    if (fade == 0)
    {
      up = true;
    }
    else if (fade == 255)
    {
      up = false;
    }
}

Not considered good coding practices:

The last if statement can be substituted for the following line, which means: if going up and 255 is reached, go down, else if going down and 0 is reached, go up, otherwise don't change direction. But it is much less readable, so I prefer the longer if statement.

up = (up && (fade == 255)) ? false : ((!up && (fade == 0)) ? true : up);

Another version: if fade is 0 or 255 (only two possibilities), go up if 0 is reached, else (can only be 255) go down, else don't change.

up = (fade % 255 == 0) ? (fade == 0) : up;


Writing int/long on Sd card I'm working on a project with SDcard, and I would like to write int and long in a file.

If I try to write 0x1954 I had 0x5419 on my file with file.write() so I did a circular shifting like:

  data=(data<<8)|(data >> (16-8)); //circular shift
  file.write((char*)&data,sizeof(data));

But with a long, I have 0x54195521 on my file instead of 0x19542155.
So I don't know how to fix this. If you have any idea, I would like to read it ! (Or another way to do it)

Thanks !

(Its not circular shifting, its bit shifting, the bits don't go round in a circle they disappear off the end and are lost forever.)

So in the library you are using you are writing bytes to the SD Card.
If you write the data 0x1954 on the card you get 0x5419.
So what is happening is you are writing the least significant byte followed by the most significant.  This is because you have take your int 0x1954 and cast it to a char[2] which contains c[0] = 0x54 and c[1] = 0x19  and then you write that out in the order c[0]c[1] et voila you have reversed you number.

The solution is to reverse the buffer before you write it:

char tmp = buf[0];
buf[0] = buf[1];
buf[1] = tmp;

HOWEVER - If you are only reading and writing from this code, who cares.  As long as you read it in backwards does it matter how it is stored on the SD Card?


Arduino starter kit example LEDS modification I just begun with the Arduino starter kit, and in the second example I would like to test some changes to learn more.

The point is to have a green LED shining, and when pressing the button the two red LEDs blink.

This is the code:

int switchState = 0;

void setup()
{
  pinMode(2, INPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);

  // the button is pressed
  digitalWrite(3, LOW);

  digitalWrite(4, LOW);
  digitalWrite(5, HIGH);
  delay(250); // wait for a quarter second
  // toggle the LEDs
  digitalWrite(4, HIGH);
  digitalWrite(5, LOW);
  delay(250); // wait fo a quarter second
}

void loop()
{
  switchState = digitalRead(2);
  // this is a comment
  if(switchState == LOW)
  {
    // the button is not pressed
    digitalWrite(3, HIGH); // green LED
    digitalWrite(4, LOW); // red LED
    digitalWrite(5, LOW); // red LED
  }
  else
  {
    // the button is pressed
    digitalWrite(3, LOW);

    digitalWrite(4, LOW);
    digitalWrite(5, HIGH);
    delay(250); // wait for a quarter second
    // toggle the LEDs
    digitalWrite(4, HIGH);
    digitalWrite(5, LOW);
    delay(250); // wait fo a quarter second
  }
} // go back to the beginning of the loop

I added a modification into the schema (a fourth LED in parallel with the green), like this:

But the added LED is not shining. It's a long time ago I finish school and I forgot a lot of things. Am I wiring the fourth LED incorrectly?

Blue LEDs have a higher Vf than green LEDs, hence much less current will pass through it, not enough to make it visible. Give it its own resistor instead of sharing the resistor with the green.


I need to restart Arduino IDE after each compilations I'm using the Arduino Due and testing an I2C Scanner, the I2C Scanner works correctly but each time I want to upload a newer version of the code I get this error message :

No device found on COM11
Send auto-baud
Set binary mode

What I need to do in this case is : remove USB, restart the Arduino IDE, reconnect USB, then it works again, one time...

It seems related to this problem : Serial port on mac only works after restarting arduino IDE

I'm not sure but What's maybe also symptomatic is I need to systematically push the restart Button of my board in order to receive something in the Serial Monitor, could it be related ?

Here is the I2C Scanner code I'm using :

// --------------------------------------
// i2c_scanner
//
// Version 1
//    This program (or code that looks like it)
//    can be found in many places.
//    For example on the Arduino.cc forum.
//    The original author is not know.
// Version 2, Juni 2012, Using Arduino 1.0.1
//     Adapted to be as simple as possible by Arduino.cc user Krodal
// Version 3, Feb 26  2013
//    V3 by louarnold
// Version 4, March 3, 2013, Using Arduino 1.0.3
//    by Arduino.cc user Krodal.
//    Changes by louarnold removed.
//    Scanning addresses changed from 0...127 to 1...119,
//    according to the i2c scanner by Nick Gammon
//    http://www.gammon.com.au/forum/?id=10896
// Version 5, March 28, 2013
//    As version 4, but address scans now to 127.
//    A sensor seems to use address 120.
// Version 6, November 27, 2015.
//    Added waiting for the Leonardo serial communication.
//
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//

#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
  while (!Serial);             // Leonardo: wait for serial monitor
  Serial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      Serial.print("Unknown error at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");

  delay(1000);           // wait 5 seconds for next scan
}

I finally solved the problem, but it's really specific and I don't know if should be on Stack Exchange. Maybe it could give some clues if someone has a similar problem one day...

I was using pin 20 and 21 on my Arduino Due which are supposed to have built-in pull-up resistor. That's what I've read everywhere and it has been said again recently in the answer of an another question I've asked : How to chooce SDA/SCL pair on Arduino Due ?.

Solution : Since I'm using SDA1 / SCL1 with Wire1 everything works like a charm. The value I get from the device are correct, no need anymore to restart the board and I can recompile again and again without any problems.

Edit : In fact, it work significantly better but I still had to use pullup resistors with these inputs. The goal was to use the MPU 9250 and it seems more stable now.


Using a water sensor with a NodeMCU make it less sensitive? I'm trying to digitalRead from a water sensor (the one in the picture) using NodeMCU v3,when I try the sensor with an Arduino board it works fine, but when I try it with an ESP8266 NodeMCU v3 it becomes less sensitive to water with some pins or doesn't work at all with the others. My question is: Is that normal or I'm doing something wrong ?

 int pin = 14;
 char printBuffer[128];
 int ledPin = 12;
 const int buzzerPin = 13;

  void setup()
  {
    pinMode(pin, INPUT);
    pinMode(buzzerPin, OUTPUT);
    pinMode(ledPin,OUTPUT);
    Serial.begin(115200);
  }

  void loop()
  {
    sprintf(printBuffer,"PIN %d level is %d\n",pin, digitalRead(pin));
    Serial.print(printBuffer);
    if (digitalRead(pin)==HIGH)
    {
      tone(buzzerPin, 100,1000);
      digitalWrite(ledPin, HIGH);
      delay(100);
      noTone(buzzerPin);
      digitalWrite(ledPin, LOW);
      delay(100);
      Serial.println("----------- ALARM ACTIVATED -----------");
    }
    else{
      noTone(buzzerPin);
      digitalWrite(ledPin, LOW);
    }
    delay(500);
   }

You are using it wrong.

That sensor (crude as it is) is an analog sensor. It's not designed to be used connected to a digital pin.

It outputs an analog voltage proportional to the resistance between the tracks in the sensing portion.

By feeding that voltage into a digital pin you are relying on the logic threshold values, plus any other components (pullup resistors, etc), to give you a "wet" or "try" signal.

Since pins differ (some have pullups, some pulldowns, some nothing, etc) and the logic thresholds are only an approximation in any case, it's doomed to failure.

You need to connect the sensor to an analog input and compare the value read to a threshold value of your choosing.  However the ESP8266 is very very poor when it comes to analog - it only has one analog input, and that is only capable of sensing between 0 and 1 volt.


RF24 tranceivers: trouble with two way communication I am using RF24 modules with my two Arduinos Leonardo with the RF24 library. My goal is to be able to press a button on the first Arduino which will light up an LED on the second Arduino, and be able to press a button on the second Arduino to light up an LED on the first Arduino. I was easily able to figure this out as a one-way transmission with the first Arduino only transmitting and the second only receiving, but I am unable to make it a two-way transmission, where each Arduino can transmit and receive at the same time.

This is my code so far:

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <RF24_config.h>

int msg[1];
RF24 radio(9,10);
const uint64_t pipe = 0xE8E8F0F0E1LL;
const uint64_t pipe2 = 0xF0F0F0F0AA;
void setup(void){
  Serial.begin(57600);
  pinMode(A0, INPUT);
  radio.begin();
  radio.openWritingPipe(pipe);
  radio.openReadingPipe(1,pipe2);
}

void loop(void){
  int charToSend[1];
  charToSend[0] = digitalRead(A0);
  if (!radio.write(charToSend,1)) {Serial.println('didn\'t send');}
  radio.startListening();
  if (radio.available()){
    bool done = false;
    done = radio.read(msg, 1);
    Serial.println(msg[0]);
    digitalWrite(13, msg[0]);
  }
  radio.stopListening();
  radio.powerDown();
  delay(10);
  radio.powerUp();
}

But the radio.write() is returning false and therefore not sending.

The main thing that I can see wrong with your sketch is that the logic of your methodology is backwards.

You are spending most of your time either with the radio asleep, or not in listening mode, so it can not receive anything.

Instead you need to spend all your time in listening mode waiting for messages to arrive, and only when the button changes state do you want to switch off listening mode and send a packet to the other end. As soon as you have done that you then go back to listening.

You can't listen while the radio is powered down, so using powerDown() and powerUp() is just nonsense.


Weird behaviour of rotary encoder values The plan is to control a NEMA 17 stepper motor with an endless rotary encoder.

First, I found a code to read the rotary encoders data on www.HowToMechatronics.com by Dejan Nedelkovski. It basically manipulates an integer and outputs it on the Serial Monitor.

Works almost perfectly except that it actually doubles the count of steps the rotary encoder does.
So a clockwise turn subtracts 1, outputs it in the SM, subtracts 1 and outputs it in the SM again. Same in the other direction with adding 1. Although being not a big deal for intended use of the rotary encoder data, I think this has something to do with the problem.

In the code down below you will find a modified version of the code from Mr. Nedelkovski. I added a few lines to move the motor a few steps in each direction.

Clockwise rotation works as I expected.
One step on the rotary equals subtract, output, movement, subtract, output, movement.

But counterclockwise rotation now adds 1 to the rotary position and subtracts it immediately, leaving the motor in moving back and forward.
But if I move the rotary very very slowly it will work.

Why are the rotary values jumping around once I added the lines?
Is there a way to solve this?

The code:

/*     Arduino Rotary Encoder Tutorial
 *
 *  by Dejan Nedelkovski, www.HowToMechatronics.com
 *
 *  to make it work with a stepper
 *  modified by me
 *
 */

#include <Stepper.h>

#define outputA 52
#define outputB 50

int counter = 0;
int dir = 0;
int aState;
int aLastState;

Stepper myStepper(200, 47, 49, 51, 53);

void setup() {

  pinMode (outputA,INPUT);
  pinMode (outputB,INPUT);

  Serial.begin (9600);
  // Reads the initial state of the outputA
  aLastState = digitalRead(outputA);

  // set the speed at 60 rpm:
  myStepper.setSpeed(60);

}

void loop() {

  aState = digitalRead(outputA); // Reads the "current" state of the outputA
  // If the previous and the current state of the outputA are different, that means a Pulse has occured

  if (aState != aLastState){
    // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise

    if (digitalRead(outputB) != aState) {

      counter ++;
      myStepper.step(50);

    } else {

      counter --;
      myStepper.step(-50);

    }

    Serial.print("Position: ");
    Serial.println(counter);
  }

  aLastState = aState; // Updates the previous state of the outputA with the current state
}

Thanks for taking your time to read this and help me. I hope that a detailed explanation will help solving the problem.

Unfortunately, I couldn't find the issue.
BUT I used another approach which worked fine.

I used the ClickEncoder library.
This time, my rotary encoder triggered 4 events per notch.

After a little research I found out, that it's possible to set the steps per notch with this library.
I used this code to initiate the ClickEncoder:

encoder = new ClickEncoder(A15, A14, A13, 4);

The first three arguments define the pins the encoder is connected to. The last argument sets the steps per notch. Now it works like a charm!

Full code:

#include <ClickEncoder.h>
#include <TimerOne.h>

ClickEncoder *encoder;
int16_t last, value;

void timerIsr() {
  encoder->service();
}

void setup() {
  Serial.begin(9600);
  encoder = new ClickEncoder(A15, A14, A13, 4);

  Timer1.initialize(1000);
  Timer1.attachInterrupt(timerIsr);

  last = -1;
}

void loop() {
  value += encoder->getValue();

  if (value != last) {
    last = value;
    Serial.print("Encoder Value: ");
    Serial.println(value);
  }

  ClickEncoder::Button b = encoder->getButton();
  if (b != ClickEncoder::Open) {
    Serial.print("Button: ");
    #define VERBOSECASE(label) case label: Serial.println(#label); break;
    switch (b) {
      VERBOSECASE(ClickEncoder::Pressed);
      VERBOSECASE(ClickEncoder::Held)
      VERBOSECASE(ClickEncoder::Released)
      VERBOSECASE(ClickEncoder::Clicked)
      case ClickEncoder::DoubleClicked:
          Serial.println("ClickEncoder::DoubleClicked");
          encoder->setAccelerationEnabled(!encoder->getAccelerationEnabled());
          Serial.print("  Acceleration is ");
          Serial.println((encoder->getAccelerationEnabled()) ? "enabled" : "disabled");
        break;
    }
  }
}


ignoring potentiometer value variations I've got a 50k potentiometer connected to an Arduino Uno. The user should adjust the hue of an Adafruit NeoPixelStrip.

I've got the following code inside the loop function:

int hue = analogRead(poti1);
int mappedHue = map(hue, 0, 1023, 0, 65535);

neoPixelStrip.fill(neoPixelStrip.gamma32(neoPixelStrip.ColorHSV(mappedHue, 255, 255)));
neoPixelStrip.show();

If I turn the potentiometer knob, the colors are updating correctly and reflect the correct hue.
But if I let go of the knob, the LEDs are flickering a little (changing their hue values ever so slightly). If I print the potentiometer values to the console, they are changing a little. If I turn the potentiometer all the way to the left, the values range from 0 ... 13 or something. This change affects the hue of the pixels.

How do I ignore those value variations? I want the user to constantly change the color, so I have to read the value constantly.

Any ideas?

You have two issues going on - noise pickup, and a potentiometer with imprecise stops at one or both ends.

The pot is the easiest to fix: What are the lowest low reading and highest high reading you can reliably get when you turn it to its stops? Use those in place of '0' and '1023' in your map() function.

Improving the noise is only slightly more involved. An exponential average is an easy filter to write and quite effective at quieting noisy data, as long the signal to noise ratio is fairly low. The basic idea is you add only a fraction of each new value and keep (1 - that fraction) of the old average; so if your chosen fraction is 0.1, you only consider 10% each new datum, keeping 90% of the current average.

avg = f*avg + (1-f)*new_value

The output of this averaging filter can be slow to respond to changes if your fraction is too small, but less effective at quieting noise if your fraction is too large.

I usually use .25, or 25% of each new point and 75% of the current average, when I'm just trying to clean up minor noise, which is what you probably have.

Here is my 25% averaging filter:

int16_t xpavg(int16_t newdat, int16_t avg){

   // (3 * avg + 1 * newdat) / 4
   return( (((avg<<2) - avg + newdat) + 2) >> 2 );
}

As you can see, I do the arithmetic in Fixed Point - just like integer arithmetic, but with an assumed binary point 2 places to the left during the computation. And I choose a fraction that represents "nicely" in binary - 1/4 in this case - to keep the arithmetic faster (since multiplication and division can be replaced by shifting).

The function just multiplies the current average by 4 and subtracts the old average (effectively multiplying by 3), adds the new value, and divides the sum by 4. (That extra "+2" rounds the fractional bits just before we shift them away). The end result is: (3*avg + newData)/4 (== 3/4*avg + 1/4*newData).

If you were to only sample the pot every second or two, you could probably observe the delay as the filter falls behind while you turn the pot and catches up when you stop. If you're sampling at 10x/sec or less, you shouldn't be able to notice.

Update:

You need to add the function xpavg() to your code, and call it each time you read a new pot value (that is "newdat"), passing it the old average as well. It returns a new average pot value, now less affected by noise. You use that new average value instead of the raw number you just read from the pot, in your hue calculation. As Duncan offered, you can - and I do - initialize the average with a raw value from the pot. You could also start it at zero but it will take a few samples to converge on the current actual pot reading. The downside of using one raw sample to start it is that if that one value is terribly noisy, i.e. way different from the pot reading, it will still take a few samples to converge.

unsigned int AvgPot = analogRead(poti1);        // initialize pot average

// Exponential averaging functions
int16_t xpavg(int16_t newdat, int16_t avg)
{
   // (3 * avg + 1 * newdat) / 4
   return( (((avg<<2) - avg + newdat) + 2) >> 2 );
}

void setup()
{
   ;    // initializations go here
}

void loop()
{
   int hue = analogRead(poti1);
   hue = xpavg(poti1, PotAvg);
   int mappedHue = map(hue, 0, 1023, 0, 65535);

   neoPixelStrip.fill(neoPixelStrip.gamma32(neoPixelStrip.ColorHSV(mappedHue, 255, 255)));
   neoPixelStrip.show();
}


Photoresistor and another switch I am using the circuit diagram below to turn ON/OFF the lights using Photo-resistor.

How can I use the Arduino to bypass the Photoresistor effect?
Let say I want to turn ON the lights even though Photoresistor doesn't want to.

Take note the 12V source is required by the LED. Knowing that Arduino must work with max 5V.

Be careful with the 12V, the Arduino can not handle 12V at its pins.

The input can be the photoresistor with a resistor to 5V (not to 12V). Use a analog input to measure the amount of light.

The output can be with a resistor to the base of the transistor.
This is an example: PighiXXX transistor
Any unused digital output can be used.
Why do you need 12V for the led ? Is it a special led ?


How to remove Arduino Due and Mega shields without bending pins? What's your suggested technique for reliably removing Arduino Due and Mega shields while minimizing the chance of bending the strip header pins?
For example, there's a similar discussion here where the asker ended up building a jig to keep everything parallel, but the main PCB was screwed down into the jig (a disadvantage). There is a heap of PCB Pullers/Extractors on the web, but they all seem to relate to edge connected cards.
I'm hoping for multiple answers / techniques. Interested to hear how you do it, or for you to upvote an answer you like. Maybe everybody is just doing the best they can with finger wriggling and manual pin straightening?

You could modify a couple of wooden clothes pegs to act as reverse pliers.


Arduino writes only one time on SD card - Data log I connected the SD card to Arduino as it's explained here. The problem is that the Arduino writes only once to the SD card and I don't understand the reason.

#include <SD.h>
#include <SPI.h>

int CS_PIN = 4;

File file;

void setup() {
  Serial.begin(9600);
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);
  Serial.print("Initializing SD card...");
  if (!SD.begin(CS_PIN)) {
    Serial.println("Card failed, or not present");
    return;
  }
  Serial.println("card initialized.");
}

void loop() {
  String dataString = "TEST";
  File dataFile = SD.open("datalog.txt");
  if (dataFile) {
    dataFile.println(dataString);
    dataFile.close();
    Serial.println(dataString);
  } else {
    Serial.println("error opening datalog.txt");
  }
  delay(1000);
}

The output on Serial Monitor:

  Arduino write only one time on SD card error opening datalog.txt error
  opening datalog.txt error opening datalog.txt error opening
  datalog.txt error opening datalog.txt error opening datalog.txt error
  opening datalog.txt error opening datalog.txt error opening
  datalog.txt error opening datalog.txt error opening datalog.txt error
  opening datalog.txt error opening datalog.txt

I also tried to use:

SD.open("file.txt", O_RDWR | O_APPEND);
SD.open("file.txt", O_RDWR | O_CREAT);

As I saw Adding data to an SD card file, but it doesn't work.

You are opening the file in read mode but should be opening it in write mode. Change File dataFile = SD.open("datalog.txt"); to File dataFile = SD.open("datalog.txt", FILE_WRITE);.

You can remove this line of code: digitalWrite(10, HIGH);.

The arduino.cc website is also an excellent source of information regarding the SD library.


MQTT (was WiFi) interference when using two nodeMCU devices I have two nodeMCU boards, one from LoLin (192.168.1.52) and one from Amica (192.168.1.53). For each nodeMCU, I have mapped its MAC address to a fixed IP address using my Movistar WiFi router. I confirm from the serial monitor that each nodeMCU is being correctly assigned to the correct IP address

My sketch is a simple IoT/MQTT client.

My problem is that if I power up both nodeMCUs, the WiFi connection is broken on both.

The WiFi portion of my sketch is

void setup_wifi() {
  Serial.println(" Booting..");
  WiFi.mode(WIFI_STA);
  WiFi.begin(SSID, PASSWORD);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    myBlink(LED_PIN, 20, 100);
    delay(5000);
    ESP.restart();
  }
  WiFi.printDiag(Serial);
  Serial.println(WiFi.localIP());
}

The output is

Mode: STA PHY mode:
N Channel: 1
AP id: 0
Status: 5
Auto connect: 1
SSID (13): MOVISTAR_xxxx
Passphrase (20): 509A8EC4Exxxxxxxxx
BSSID set: 0

192.168.1.53 (or .52 on the other device)

I realise that the symptoms are consistent with clashing IP addresses, but to confirm, both the serial diagnostics and the DHCP report from my router confirm that the two devices are on different IP addresses.

My bad!

Although my symptoms were consistent with WiFi interference, the interference was actually at the MQTT level.

The root cause was that I hadn't realised that each MQTT client must have a unique client ID. When the 2nd nodeMCU connected, it disconnected the first nodeMCU from MQTT, which then went into a reboot sequence to recover, which then returned the favour to the other nodeMCU.


Arduino with bmp280 sensor not entering void loop I've been working on a project in which I need to know my altitude. For this purpose I've been using the BMP280 sensor. But I have an issue.
I've been trying to test if the sensor works with the program "bmp280_sensortest.ino", already included in the library. When I open the serial monitor the message "BMP280 Sensor event test" is displayed, indicating that there is a valid sensor on board. Below that the temperature, pressure and altitude data should be displayed, but nothing happens.
I've added a simple Serial.print("hello") at the start of void loop(), but not even that is displayed. The program doesn't seem to enter void loop() and I don't know why.
Here is the code:
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_BMP280.h>

Adafruit_BMP280 bmp; // use I2C interface
Adafruit_Sensor *bmp_temp = bmp.getTemperatureSensor();
Adafruit_Sensor *bmp_pressure = bmp.getPressureSensor();

void setup() {
  Serial.begin(9600);
  Serial.println(F("BMP280 Sensor event test"));

  if (!bmp.begin()) {
    Serial.println(F("Could not find a valid BMP280 sensor, check wiring!"));
    while (1) delay(10);
  }

  /* Default settings from datasheet. */
  bmp.setSampling(Adafruit_BMP280::MODE_NORMAL,     /* Operating Mode. */
                  Adafruit_BMP280::SAMPLING_X2,     /* Temp. oversampling */
                  Adafruit_BMP280::SAMPLING_X16,    /* Pressure oversampling */
                  Adafruit_BMP280::FILTER_X16,      /* Filtering. */
                  Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */

  bmp_temp->printSensorDetails();
}

void loop() {
  sensors_event_t temp_event, pressure_event;
  bmp_temp->getEvent(&temp_event);
  bmp_pressure->getEvent(&pressure_event);

  Serial.print("hello");
  Serial.print(F("Temperature = "));
  Serial.print(temp_event.temperature);
  Serial.println(" *C");

  Serial.print(F("Pressure = "));
  Serial.print(pressure_event.pressure);
  Serial.println(" hPa");

  Serial.println();
  delay(2000);
}

Any reply is greatly appreciated.
edit:
if I remove
!bmp.begin()
from the if statement and replace it with a 1 it enters the void loop but it displays 0°C and 0pa

It could be a faulty library/sensor, most likely the sensor, sometimes sensors can begin but then another connection could be faulty or the chip itself is faulty and so the Arduino might just be waiting forever for a response that will never come.
To see where it gets stuck, you can add Serial.println(F("1")); after bmp.setsampling then Serial.println(F("2"));  after bmp_temp->printSensorDetails to see where exactly it's getting stuck
One thing I also like to do is to buy two/three of a sensor, so that I can replace a sensor with another one. That way if a piece of code doesn't work for all three sensors then I can pretty sure it's a problem with the code and not the device. Not sure if you have a spare sensor to try that but I would recommend it in future


ESP32 reset loop when using wifi.h I have a strange behavior, using ESP32 devkit v.1 boards.
Everything works, I can upload blink sketch, serial works, led blinks.
However, once I upload any sketch which is using the wifi.h (and utilizing it for example calling WiFi.mode(WIFI_STA);), upon upload, the board keeps resetting the serial connection, stays up for not more then 1 second, resets again, and so on.
I could not debug the issue, since serial is unusable. Any ideas what is wrong? I did a fresh ArduinoIDE, ESP32 board manager install, etc. and normal sketches work flawlessly.

The USB cable was too long, and hence power loss.

Sorry, I figured it out a day after I asked this question.


Arduino time(milli) and pressure sensor I've succeeded to get an Arduino to work with a pressure sensor.

What I want to do is

when I put pressure on the sensor, after 5 minutes the led lights on.
it starts over again if there's no pressure on the sensor.

Here's the program:

// FSR is verbonden met analoog 0
int fsrAnalogePin = 0;
// De LED is verbonden met pin 11 (pmw pin)
int LEDpin = 11;
// De analoge waarde van de fsr spanningdeler
int fsrWaarde;
// De helderheid van de led tussen 0 en 255
int LEDhelderheid;

void setup() {
    // start de serial monitor
    Serial.begin(9600);
    pinMode(LEDpin, OUTPUT);
}

void loop() {
    fsrWaarde = analogRead(fsrAnalogePin);
    // print ‘Analoge waarde’
    Serial.print(“Analoge waarde = “);
    // print de fsrwaarde op de monitor
    Serial.println(fsrWaarde);

    // maak van getallen tussen 0 en 1023 getallen tussen 0 en 255
    LEDhelderheid = map(fsrWaarde, 0, 50, 0, 255);
    analogWrite(LEDpin, LEDhelderheid);
    delay(100);
}

I've got this for the pressure sensor... now I need to combine it with 5 minutes and the led lights on when it's reached that 5 min of pressure.

i managed to do this but it aint enough...

unsigned long currentTime;
unsigned long startTime;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  currentTime = millis();
  startTime = currentTime;
}

    void loop() {
  currentTime = millis();
  // put your main code here, to run repeatedly:
  Serial.println(currentTime);
  delay(1000);

  if(currentTime-startTime > 6000) {
Serial.println("1 minuut voorbij");
startTime = currentTime;
  }
}

Try this:

unsigned long pressureOnTime; //millis() time when pressure switch is first turned on

const unsigned long ledOnAfterTimeThreshold = 300000; //5 minutes * 60 sec * 1000 mSec
int pressureThreshold = 1; //minimum analog reading from pressure sensor considered to be "on"

const int fsrAnalogePin = 0;
const int ledPin = 11;

int ledState = LOW;
int pressureState = LOW;

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

void loop() {
    checkPressureSwitch();

    //do other stuff here
}

void checkPressureSwitch() {
    if( analogRead(fsrAnalogePin) >=  pressureThreshold )
    {
        handlePressureOn();
    }
    else
    {
        handlePressureOff();
    }

    digitalWrite(ledPin, ledState);
}

void handlePressureOn() {
    if ( pressureState == LOW )
    {
        //pressure switch was off, but is now on
        pressureOnTime = millis();
        pressureState = HIGH;
    }

    else if ( millis() - pressureOnTime >= ledOnAfterTimeThreshold )
    {
        ledState = HIGH;
    }
}

void handlePressureOff() {
    ledState = LOW;
    pressureState = LOW;
}


Python Arduino Serial Communication Speed Background : Im controlling serial manipulator using Arduino Uno with Servo Shield. Servo work at 20 ms, so i would like to send command atleast every 2.5ms. Command sent from PC.

I send 8 bytes of data from my python code on PC at 250k Baudrate. If i send it every 25 ms, my robot could respond and everything works fine. But if i send every 2.5 ms, my system wont work.

Here my arduino code,

#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
int x,temp;

int sudutT0(long int p)
{
  int u = 3600+((405*p)/180);
  return u;
}

void setup() {
  Serial.begin(250000);
  Serial.println("Joint 2 Test!");
  pwm.begin();
  pwm.setPWMFreq(50);

  Wire.setClock(1000);
  for (uint8_t pin=0; pin<16; pin++)
  {
  pwm.setPWM(pin, sudutT0(90),4095);
  }
  pwm.setPWM(3, sudutT0(150), 4095);
}

void loop() {
    if(Serial.available() == 8){
      if(Serial.read() == 0xF5)
      {
        //Joint 1
      temp = Serial.read();
      x = sudutT0(temp);
      pwm.setPWM(0,x,4095);
      // Joint 2 Servo
      temp = Serial.read();
      x = sudutT0(temp);
      pwm.setPWM(1,x,4095);
      x = sudutT0(180-temp); //810 - theta
      pwm.setPWM(2,x,4095);
      //Joint 3 - 6, Gripper
      for(uint8_t u = 3; u<8; u++)
      {
        temp = Serial.read();
        x = sudutT0(temp);
        pwm.setPWM(u,x,4095);
      }
      //delay(100);
      }
    }
}

Is there anything that i miss, that make my system could not respond if i send signal every 2.5 ms?

All of the code takes time. It takes ~0.2 ms just to send the 8bytes at 250k, then you have to process the data. I would suspect that all that is taking longer then 2.5 ms and so by the time you read again, you have more then 8 bytes in the buffer, and eventually it overflows. I would try decreasing from 25ms to 24 and re-test, then reducing again. you may be able to find the lower limit of what will work reliably. This is assuming there is a need for it to update faster then 40 times a second, if not then just stay at 25ms


Possibilities and limitations for onboard data acquisition I could define myself as a "nerdy cyclist", so while my interest in Arduino is steadily growing (have not bought or used yet), my first idea for a project would be:

Instrument a bicycle with some sensors (accelerometer, reed switch, etc) and an Arduino;
Ride long distances (that is, four hours or more, sometimes non-stop);
When at home, download some sort of "data file" (from SD card, I think);
Analyze results with Python/Matlab/whatever.

So my questions:

Is any model of Arduino suitable for this purpose?
What is the expected sample rate vs number of channels? 100Hz per channel would be excellent for my purposes, for example.
Can I keep incrementally saving to SD "forever" (that is, while battery and card space are available)?

First of all your idea project is feasible. And to answer to your questions:

There is no right Arduino for your project simply because theoretically every Arduino board can do the job. But as you said it has to be portable you might use Arduino nano/mini or even Uno if you have enough room or space.
The acquisition rate depends on the on the type of sensor you have. So if you have let's say one analog reading you can use the built in function in Arduino which is capable of making about 10000 readings at time. So if you have multiple outs you can easily for the calculation. There are also sensors which has a digital output in this case in order to read your value you communicate with Tue sensor board through Two wire interface or I2C communication interface, for this there is a library you can use. Usually the speed at which this communication work s very high, at 100kHz( if I'm not wrong).

3.Yes you can save data on the SD card until you don't exceed the memory or the battery doesn't die.

I have a suggestion for your project, as you're going to acquire some sort of data and then analyze it on your computer, do less calculations on your Arduino board and let the PC handle the hard work.

Useful links:

Reference to the two wire communication: http://arduino.cc/en/reference/wire
Reference to the SD card reading on Arduino: http://arduino.cc/en/Reference/SD


ESP8266 Webserver ESP8266WebServer variable html page (not as one const char) The aim is to display a non-static html page depending on some variable condition.

The code I created hast the problem, that the esp8266 is ressetting in the moment I request the page.

const char htmlIndexHeader[] PROGMEM = R"=====(

    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test</title>

Hello World

)=====";

const char htmlIndexProgress1[] PROGMEM = R"=====(

lorem

)=====";

const char htmlIndexProgress2[] PROGMEM = R"=====(

ipsum

)=====";

const char htmlIndexFooter[] PROGMEM = R"=====(

)=====";

char htmlIndexAll[2000];

void handleRoot()
{
  Serial.println("GET /");

   strcpy(htmlIndexAll, htmlIndexHeader);

   if(var1==true)
   {
     strcat(htmlIndexAll, htmlIndexProgress1);
   }

   if(var2==true)
   {
     strcat(htmlIndexAll, htmlIndexProgress2);
   }

   strcat(htmlIndexAll, htmlIndexFooter);

  server.send(200, "text/html", htmlIndexAll);
}

If I display a static page the esp8266 does not restart at page request.

Compiler can't differentiate the PROGMEM strings from constant strings in SRAM strings. Both are const char*. But the PROGMEM string must be handled differently. For that reason _P variants of functions exists.

You should use stcpy_P and strcat_P functions.

Note: On esp8266 some functions of Arduino core use a trick to identify PROGMEM strings by their specific address range.


Weird characters in Serial Monitor and not functioning ESP8266 ESP-12e I did a bit of playing with my new ESP-12e, but suddenly it kind of fails on me. It gives me some weird looks it didn't give me (as much) before.

This is what the Serial Monitor prints when I try to run a very simple sketch. When I restart the module, it just adds some more of these chars.
The following is the code for that:

const int statusLED = 16;

void setup() {
  pinMode(statusLED, OUTPUT);
  digitalWrite(statusLED, HIGH);

  Serial.begin(115200);
  Serial.write("The ESP-12e has started.");
  delay(500);
}

void loop() {
  delay(1000);
  digitalWrite(statusLED, LOW);
  delay(1000);
  digitalWrite(statusLED, HIGH);
}

This doesn't even involve the WIFI...

These are my board settings:
Board: Generic ESP8266 Module
Flash mode: QIO
Flash frequency: 40MHz
CPU frequency: 80MHz
Flash size: 4M (3M SPIFFS)
Upload speed: 115200

And finally, if it might help, how I connected the module:

All connections are solid, so that shouldn't be a problem. The connection board has GPIO15 printed on it twice, but the one I connected to the LED is actually GPIO16. I noticed that the onboard LED of the ESP-12e doesn't light on anymore.

I use the CP2102 USB to UART module.

Thanks!
Rogier

Check what baud rate is serial window displaying. It should be the same as defined in your code.


LM35 at higher temperatures I have a question concerning the LM35 sensor: if I'm not too concerned about accuracy (I don't mind having 2 or more degrees off), is it possible to use the LM35 sensor at higher temperatures than the normal range? The project that I'm thinking of using this sensor, temperatures should reach 200 degrees, maximum.

Thanks!

No, you cannot.  The LM35 is rated for an absolute maximum junction temperature of 150°C.  Any higher than that and you will damage it.

For temperatures above that you are better using a thermocouple.


Arduino Standalone construction In tutorial - https://www.arduino.cc/en/Main/Standalone , they have used voltage regulator. Can we able to do without Voltage regulator ?(to compact the circuit), If so what should the voltage & current value in Atmega328?

That's actually quite an involved question to answer. The short answer is "Yes, you can do without the regulator as long as you get the voltage right".

And that is where it gets tricky.

The datasheet states:

  Operating Voltage:

  1.8 - 5.5V

So you can power it from two or three AA batteries, for instance (3V - 4.5V). However, that is not the whole story.

The voltage you provide it with dictates what frequency the chip can reliably run at. Later in the datasheet is this nice little graph:

Since the normal Uno-like arrangement runs at 16MHz you're looking at a minimum voltage of around 3.8V - 4V (it's actually quite hard to work out from that graph).

But if you are willing to reduce your clock speed to 8MHz (which is what the 3.3V Arduino "Pro" boards run at) then you can drop right down to about 2.5V.

At a 2.5V lower limit with 3 AA batteries it would equate to a minimum voltage of 0.83V per cell, which is below the normal minimum accepted "flat" voltage of 0.9V per cell.

So powering from 3 AA batteries with a clock speed of no more than 8MHz would give you probably the best run-time.  Note, also, that a decrease in clock frequency decreases the current consumption as well - the slower you run the chip the less current it needs. You can see that in this graph in the datasheet:

And yes, as you can see, the lower the supply voltage the lower the current as well. So as the batteries run down and the voltage drops so does the current, reducing the speed at which the batteries will run down.

As you can see, if you don't mind the supply voltage changing (which of course will affect everything else in the circuit, so you need to check those out first), running directly from batteries without a regulator can actually have advantages. But as I say, you need to check what else you are running in the circuit to make sure it doesn't mind if the power supply voltage drifts.

And don't forget, also, that the supply voltage affects the ADC readings, since they are referenced to that voltage as well.


Bluetooth Trancievers for arduinos Would it be possible to use to of these on two separate arduino's, to send and receive information? I am having difficulties understanding the chinese-english descriptions and haven't seen any documentation on doing this. There would be no phone involved. There would only be two arduino's with a Bluetooth module on each of them sending and receiving data from each other.

The boards in your link look funny.  Typical boards like this include the "bluetooth circuit" which piggy-backs onto that board, and is soldered at all those little pads.

Have a look at say, the HC-05 board ~  https://www.google.com.au/search?q=hc05+bluetooth+module&tbm=isch

It's easy to see the part that's missing from the one in your link.

For these HC-05 boards, it's possible to pair two together.  They need to be configured as "Master" and "Slave" though.  Some bluetooth boards can do slave-mode only, so be careful before you purchase.


error: no '' member function declared in class 'SonarSRF08' Hi, I am a pretty novice coder and I am getting this error consistently with a library I have installed. Here is the code I am trying to run:

#include <Wire.h>
#include <SonarSRF02.h>
#include <SonarSRF08.h>

#define leftAddress ( 0xF2 >> 1)
#define rightAddress ( 0xE0 >> 1)
#define mainAddress ( 0xF8 >> 1)
SonarSRF02 LeftSonar;
SonarSRF02 RightSonar;
SonarSRF08 MainSonar;

char unit = 'c'; // 'i' for inches, 'c' for centimeters, 'm' for micro-seconds

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

    LeftSonar.connect(leftAddress);
    Serial.println("Left SRF02 US-Sensor ");
    Serial.println(LeftSonar.getSoft());

    RightSonar.connect(rightAddress);
    Serial.println("Right SRF02 US-Sensor ");
    Serial.println(RightSonar.getSoft());

    MainSonar.connect(mainAddress);
    Serial.println("Main SRF08 US-Sensor ");
    Serial.println(MainSonar.getSoft());
}

void loop() {
    float sensorReading = 0;

    sensorReading = LeftSonar.getRange(unit);
    // print out distance
    Serial.print("Distance from left: ");
    Serial.print(sensorReading);
    Serial.print(" ");
    Serial.print(unit);
    Serial.println();

    sensorReading = RightSonar.getRange(unit);
    // print out distance
    Serial.print("Distance from right: ");
    Serial.print(sensorReading);
    Serial.print(" ");
    Serial.print(unit);
    Serial.println();

    sensorReading = MainSonar.getRange(unit);
    // print out distance
    Serial.print("Distance from main: ");
    Serial.print(sensorReading);
    Serial.print(" ");
    Serial.print(unit);
    Serial.println();
}

My project is using an SRF08 sensor with an Arduino Mega 2560

Please note that I did not try to run your code on my Mega because I don't have SRFs
However, here is what I tried to recreate your error:

I went to the arduino homepage and downloaded the 1.0.5 version.

I downloaded the zipped library from this page SRF08 Ultra Sonic Range Finder

I imported the library into the arduino IDE. For this, I had to unpack the .zip and rename the folder of the library because arduino complained about non-ascii characters. I just called the enclosing folder "arduinoSRFmaster" without dashes. After that it let me import the library the usual way:

After that I copied your code into a new sketch and hit Ctrl + R to compile and verify. It compiled just fine:

(Picture updated for compiling against MEGA)
Please provide more information, like yor OS, Arduino Version, where you got the SRF Library from etc. if that didn't help.


What is the difference between serial begin() and wire.setClock() for I2C communication? I am a new Arduino IDE user and have a simple question below
For I2C transmission speed setting, there are serial begin() and wire.setClock(). Some sample codes just use Serial.begin() without Wire.seClock(), some use both as shown below. What is the real differences between them? When to use just serial and when to use both of them? Thanks.
void setup() {
  Serial.begin(9600);          // start serial communication at 9600bps

  Wire.begin();                // join i2c bus (address optional for master)

  Wire.setClock(400000); //Increase  I2C clock rate to 400 kHz
}

Serial has nothing to do with Wire/I2C communication. The examples only have this, because mostly they use Serial out- and input for interaction in the example codes (like showing the data of an I2C sensor on the Serial Monitor).
If you don't want to use the Serial Montior/Serial communication, then you can leave all the calls to Serial out.


Battery Solution for ESP8266 and HC-SR04 I'm working on a project that includes an ESP8266 (requires 3.3v input (250 mA peak)) and a HC-SR04 (requires 5v 20 mA peak). I'm making it battery/solar powered.

I'm trying to keep costs down as well as make a system that works reliably and has good longevity.

I'll be waking the device every 15 minutes and keeping it in deep sleep at the other times.

Originally I was going to use a battery source over 6v, like a 6 cell AA rechargeable battery pack, a 10v or so solar panel, and a breadboard type voltage regulator that conveniently provides 3.3v and 5v on the same board. This seems to waste a decent amount of power though.

Right now I'm looking into using a 2 AA rechargeable NiMH batteries, a 5v solar panel, a 3.3v step up voltage booster, and a 5v step up voltage booster. 5v step up voltage boosters are everywhere and cheap because of their uses for portable cell phone chargers. 3.3v step up voltage boosters on the other hand are more expensive and harder to find.

Looking for any advice or affirmation that I'm on the right path. Thanks!

A time a go when searching for some circuit to provide power to ESP and also being capable of charging batteries I came across this reply here. Is intended for usb charger/Li-Ion batteries but maybe it could suit your needs too and be adapted. In the output the circuit presented there, you could use some LDO like  MCP1825S (or even the MCP1825 with extra information possibilities). Never test the circuit yet, so can not provide any good answer about how long it provides juice to ESP.


Sparkfun CAN Shield BMW OBD2 reading I bought the CAN-Shield from Sparkfun https://www.sparkfun.com/products/13262 and I also got the Uno from Sparkfun just to be sure everything works fine.

Some info about my car:

BMW E91 2006
OBD2 is available
KWP 2000 and other lines are available
like the ones with the same baud rates from the demo

I tried the SparkFun_CAN_Demo which is available on their website and GitHub.

My output is that
CAN init is successful but I don´t know if that´s true...
If I try to read the RPM, for example, I get a buffer with a size of 1 -> " ".

My questions are:

Did I something wrong with the MCP2515 how do I know if it´s dead?
Does anybody know if the demo is working properly or not?
What´s the right way to get data from an BMW with OBD2?

First off I cannot say much about the library that you are using I have't tried that one yet as for the shield i have some of those and there are two versions of them check your PIN outs on them the cs pin is either on d9 or d10

the other thing is make sure that you are in the right operation mode ie. Normal and maybe give this library a try I have had lots of success with this one:
https://github.com/coryjfowler/MCP_CAN_lib

as for the baud rate I have tried all types of ways of getting the right baud rate for certain vehicles but the best remains start small and step it up till you get the one that gives you reply

make sure that you ground the Arduino to the car as well it works without that but sometimes it does nothing If you are using the OBDII cable it should be grounded by default


Sending sound signal of computer's sound card to arduino how can i send the signal of sound card to arduino? I want to send sound signal of computer's sound card to Arduino just connect a wire from card to Arduino.. and then i will process it by programming of Arduino after that processing the signal will send via wifi... this is my ideal idea.. how can i do this thing? can i interface Arduino via sound card output pin/jack? can i catch the signal of sound card in Arduino?

Did you a look at this ?
Don't expect to play good quality audio through an Arduino, it is not powerful enough for that. Also the Arduino's AD converter is way to slow for anything but telephone quality audio !


How can I create analog signal which is similar to PMT(Photo Multiplier Tube) pulse using analog write? I have developed a circuit to process the PMT pulse output, For the testing, I need an artificial signal which is similar to the PMT pulse.How can i use the AnalogWrite() to create such type of signal.

Short answer: You can't.

The Arduino can't do analog output at all, much less matching a specific analog waveform of ≈40ns duration.

PWM on the Arduino simulates constant analog voltages using square wave pulses of variable duty cycle. It has no support for creating analog waveforms of any type, much less ones with such a short duration.

EDIT

As mentioned in this thread: Generate a ramp input with an Arduino Uno

You could use a resistor ladder to create a roll-your-own DAC, and then use direct port register manipulation (not digitalWrite) to set the pins controlling your resistor ladder and get a crude approximation of your waveform.


Unusual LCD behaviour Can someone please tell me what's going on with my LCD screen and how I can fix this issues below?

I have the following:

Arduino Uno R3 w/ ATMEGA 328P-PU
16x2 LCD
TowerPro MicroServo SG90
DPDT Slide Switch w/ 120 ohm resistor

Objective:
Read the sensor value (If switch is on or off), and move a servo accordingly while displaying switch state on LCD.

Issue:
LCD display seems to receive random data during program run (see image). All starts up well, and as soon as a few seconds have lapsed in the void loop(), the screen becomes garbled. Also, the switch value (while debugging) gets a zero reading while HIGH, acting accordingly as if the switch was off. The servo motor runs as it should, but gets random pulses every now and again where it starts to buzz, but doesn't turn.

Images:
Three images below.

Schematic:

Coding:

#include <LiquidCrystal.h>
#include <Servo.h>

const int sensorPin = A0;    // select the input pin for the potentiometer
int ledPin = 13;      // select the pin for the LED
int sensorValue = 0;  // variable to store the value coming from the sensor
int oldPos = 0;
int pos = 0;
int oldStat = 0;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
Servo servo;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.setCursor (0, 0);
  lcd.print("Starting up FSS!");
  delay(700);
  lcd.clear();
  lcd.print("Init SERVO...");
  delay(500);
  servo.attach(9);
  lcd.clear();
  lcd.print("SERVO Success!");
  delay(400);
  lcd.clear();
  lcd.print("Testing SERVO...");
  servo.write(0);
  delay(200);
  servo.write(90);
  delay(200);
  servo.write(45);
  delay(300);
  lcd.clear();
  lcd.print("SERVO Running!");
  lcd.clear();
  lcd.print("Select AUX Source");
  pinMode(ledPin, OUTPUT);
}

void loop() {
  lcd.clear();
  lcd.setCursor (0, 0);
  lcd.print("Select AUX Src");
  lcd.setCursor(0, 1);

  sensorValue = analogRead(sensorPin);
  Serial.print("Sensor: ");
  Serial.println(sensorValue);

  if(sensorValue == 0){
    //if(sensorValue = oldStat){
      oldStat = sensorValue;
      digitalWrite(ledPin, LOW);
      lcd.print("Switch is OFF");
      pos = 45;

      Serial.println("Switch is OFF");
    //}
  } else{
    digitalWrite(ledPin, HIGH);
    lcd.print("Switch is ON");
    pos = 120;
    Serial.println("Switch is ON");
  }

  if (pos != oldPos){
    servo.write(pos);
  }

  oldPos = pos;

  delay (700);
}

Insufficient decoupling. Put a 100nF cap on the supply lines at the LCD and a 100uF cap on the supply lines at the servo.


Run website / Javascript game from a Arduino UNO device? I apologise if this is a dumb question, but I'm trying to find information on whether or not this is possible. I'd like to build a arcade machine to play my custom Javascript 2D game. The game currently runs in the browser (of course), but is it possible to execute the code in the Arduino. I'd like to make an arcade machine that runs from the Arduino and connect the game controls to a joystick. Can anyone tell me is this is possible, or any suggestions about how I can achieve this without rewriting the application.

I found the below link that has some information but this is for a PI
https://www.raspberrypi.org/forums/viewtopic.php?t=194808

The Arduino cannot run Javascript, no.

It could serve Javascript from an SD card to a web browser running on a PC / Pi / Phone, etc, but there is no way it can run it itself.


How to use different device address for MCP23017 so I can use multiple chips? I want to use more than 3 MCP23017-E/SP DIP28 chips so I can use many digital pins. I use Adafruit-MCP23017-Arduino-Library. I tried this solution but only device address with 0x00 is working.

The question is what device address should I use for additional chip?

#include "Adafruit_MCP23017.h"
Adafruit_MCP23017 mcp1;
#define addr1 0 // tested 1,2,3,4,5, 0x01, 0x02, 0x20, 0x21 but only 0 and 0x00 is working.
void setup()
  {
    mcp1.begin(addr1);
    mcp1.pinMode(0, INPUT); //pin 21 on chip
    Serial.begin(9600);
  }

  void loop()
  {
      if(mcp1.digitalRead(0)== HIGH )
      Serial.println("HIGH");
  }

I share my solution with 7 MCP23017 chip , 7x14 pins=98 pins using adafruit library.

Connections:

addr 0 = A2 low , A1 low , A0 low  000
addr 1 = A2 low , A1 low , A0 high 001
addr 2 = A2 low , A1 high , A0 low  010
addr 3 = A2 low , A1 high , A0 high  011
addr 4 = A2 high , A1 low , A0 low  100
addr 5 = A2 high , A1 low , A0 high  101
addr 6 = A2 high , A1 high , A0 low  110
addr 7 = A2 high, A1 high, A0 high 111

Connect pin #12 of the expander to Analog 5 (i2c clock)
Connect pin #13 of the expander to Analog 4 (i2c data)
Connect pins #15, 16 and 17 of the expander to ground (address selection)
Connect pin #9 of the expander to 5V (power) // operation voltage is 1.8 to 5.5
Connect pin #10 of the expander to ground (common ground)
Connect pin #18 through a ~10kohm resistor to 5V (reset pin, active low)

Input #0 is on pin 21 so connect a button or switch from there to ground

Code:

#include <Adafruit_MCP23017.h>

Adafruit_MCP23017 mcp1; // chip 1
Adafruit_MCP23017 mcp2; // chip 2

#define addr1 7 // 7 = A2 high, A1 high, A0 high
#define addr2 0 // 0 = A2 high, A1 high, A0 high
void setup()
  {
    Serial.begin(9600);
    mcp1.begin(addr1);
    mcp2.begin(addr2);

    mcp1.pinMode(0, INPUT); //pin 21 on chip
    mcp2.pinMode(0, INPUT); //pin 21 on chip

  }

  void loop()
  {
      if(mcp1.digitalRead(0)== HIGH )
      Serial.println("HIGH");
      delay(1000);

      if(mcp2.digitalRead(0)== HIGH )
      Serial.println("HIGH 2");
      delay(1000);
  }


How does an analog input pin work? I have a potentiometer of 10k and I connected it this way:

5v -> potentiometer -> analog input pin of Arduino

When I turn the potentiometer I change the resistance of the circuit but in the Arduino documentation they say that an analog pin in INPUT mode will have 1 megaohm resistance. So, for example, if I turn the potentiometer to the middle it will generate 5k of resistance + 1 megaohm of the analog pin it will result in a tiny, very tiny current. If I use U = R x I across the potentiometer it will be:

U = 5000 x 0.0000001

U ~ 0 across the potentiometer. So U will be 5 V at the analog input because there was no drop of voltage in the circuit. If turn the potentiometer all way up to 10k resistance the voltage in the analog input will also be 5 V because the voltage drop across the potentiometer is still really small.

I know that an analog pin in INPUT mode will read 0 V as 0 and 5 V as 1023. But as I showed you it should always read 5 V even when I turn the potentiometer all way up because the voltage is not being changed. I know I am wrong cause when I log the input pin it shows different values as I turn the potentiometer. So how does this work?

The potentiometer and the internal resistance form a voltage divider. The voltage created by this voltage divider is essentially indistinguishable from 5V regardless of what the pot is set to because the internal resistance is so high.

What you want to do is to create an external voltage divider that will cause the voltage to vary full scale between 5V and 0V. You do so by connecting one end of the pot to 5V and the other end to 0V, and drawing the voltage from the wiper.


Is Arduino reliable for serious tasks, such as medical machines? I'm just getting started with Arduino, and it has a LOT of uses, however, I would like to know how reliable is it? Can it be used for medical purposes (Measure vital signs, or to help surgeons perform surgeries), if it depends on the board, which one is the most accurate and reliable?

I know most robotic tasks will rely on the quality of the servo to interpret the Arduino commands, and sensors, and even the coding/logic, but we can replace/recode all of those things, but when it comes to the main board it gets more complicated

You should NOT trust using an Arduino for life safety measures (medical purposes).

This discusses the reliability of an Arduino pretty well- https://electronics.stackexchange.com/questions/15535/reliability-of-the-arduino-platform-for-industrial-use