Serial Communication Not Receiving Entire String I have an Arduino connected to a pico motor driver that is supposed to take a number of steps for a specific number of triggers that gets from a source (i.e. waveform generator). I've setup the code so that it would ask the user to input number of steps and number of triggers. For example, if I want the motor to take 10 steps once it got 60 triggers, I should input s10; and t60; separately into Serial Monitor.

In addition, I want to be able to change the number of steps and triggers any time that I want. However the problem is that sometimes Arduino doesn't receive the input string entirely for the first time. Sometimes it works on the second try. Or even not at all. I really appreciate if someone can give a hint on why this is happening.

This is a simple version of the code (without the parts that move the motor):

#include<String.h>

long int steps;
long int num_triggers;
long int newtrigger;
long int newstep;
long int oldtrigger;
long int oldstep;

const int main_control = 0;
int triggers_count;
bool motor_trigger = true;

void setup() {

 Serial.begin(19200);
 Serial.println("Please enter chosen number of steps and triggers.");
 Serial.println("Example: \n If you want the pico-motor to take 10 steps per 40 triggers,");
 Serial.println(" write 's10;' and press enter then do the same for 't45;'(Order doesn't matter).");
}

void loop() {

  while (num_triggers == 0 || steps == 0) {

    getcommand(&steps, &num_triggers);

  }

  attachInterrupt(main_control, trigger, RISING);  // it starts looking for trigger

  if (motor_trigger == false) {

    getcommand(&steps, &num_triggers);
  }

  else if (motor_trigger == true) {

    motor_trigger = false;
    detachInterrupt(main_control);

    if (triggers_count <= (num_triggers - 1)) {

      getcommand(&steps, &num_triggers);

    }

    else {

      for (int i = 0; i < steps; i++) {

        oldstep = steps;
        oldtrigger = num_triggers;
        getcommand(&steps, &num_triggers);

        if (  num_triggers != oldtrigger || steps != oldstep) {
          break;
        }
      }
    }
  }
}

void trigger(void) {

  motor_trigger = true;
  triggers_count++;
}

void getcommand (long int *newstep, long int *newtrigger) {

    char   char_input;
    String string_input;
    String output_1;
    String output_2;

  while (Serial.available()) {

    char_input = Serial.read();
      if (char_input == ';'){
    Serial.println("done");

      }
      else{
    string_input += char_input;
    delay(500);
    }
  }

  Serial.println("Getting input...");
  Serial.println(string_input);
  Serial.println("Input printed.");

  int inputlen = string_input.length();
  output_1 = string_input[0];

    for ( int i = 1; i < inputlen; i++ ) {
      output_2 += string_input[i];
    }

      if ( output_2.toInt()<=0 && inputlen>0 ){   // check if there's an error

        Serial.println("Error with input number");
        delay(5000);
        Serial.println("Reading the input string");
        Serial.println(Serial.readString());
        Serial.println("Done reading the input string");
        }

    if (output_1 == "s") {

      *newstep = output_2.toInt();

    }

    else if (output_1 == "t") {

      *newtrigger = output_2.toInt();
    }

  }

I can see several issues:

If the Serial buffer contains more than one command already, you'll read it too. For example serial buffer contains "s43;t25;" and  the input_string would be something like "s43t25". This is highly to happen if you send those characters in less than 3seconds (as you have delay(500) for each appended character). You have to stop reading from buffer if you detect ';'.
Parsing of commands is also pretty weird. You are blocking for some time, so you can detect 's'/'t' and then use Serial.parseInt(); with Serial.setTimeout(1000); to do similar but much faster get command.
Variables set inside of ISR (function trigger is called from ISR) must be volatile. Otherwise it might be optimized out or into register by compiler.

Anyway, if you want to read whole commands try the serialEvent() example. Just change checking for '\n' to ';' and then you can parse that command in your way when it's complete.


Is the Arduino Due compatible with a Dual VNH5019 Motor Driver Shield? I'm planning on buying an Arduino Due and there is a shield I would like to attach to it. I have seen a lot of things saying that some shields are not compatible with Arduino Due... I was wondering if the Arduino Due is compatible with the Dual VNH5019 Motor Driver Shield.

This is where I'm buying it from if you need any extra information on the items:

The Arduino Due
The Dual VNH5019 Motor Driver Shield

Answers greatly appreciated! If you need any specifications let me know.

ok so I went ahead and bought the arduino due and officially tested it out and the Arduino Due is compatible with the Dual VNH5019 Motor Driver Shield!

hope this helps!


Arduino ligths on/off clapping hands I'm new to Arduino and I'd like to realize a system using Arduino One and SparkFun Electret Microphone Breakout (BOB-09964) to turn on/off lights clapping my hands. https://www.sparkfun.com/products/9964

What are the components I need? I'm going to buy them and I don't want to buy components which I will not use soon (so no starter kits but only a breadboard, resistors, LEDs, etc...).

Sorry for this basic question but as I said I'm new to this world.

If you start from the beginning of the project, instead of trying to jump in half way through, you'll know precisely what components you need.

Your first step shouldn't be trying to order components, but to identify (through research) how the technology works.

Second is to find out how it can be implemented, by looking at existing schematics and designs that other people have created.

Third is to design your own schematic.

Fourth is to prototype it.  It's only at this stage that you should be thinking about what components to order.

Go back to stage one and do the research. Thanks to the likes of Google it'll probably only take you a few minutes.


Code example SPI multiple slaves Arduino DUE I'm trying to get 2 devices (camera and sd card)to work on the SPI interface with an Arduino DUE.  I'm having trouble finding example code online showing how to communicate with multiple slaves on the DUE as I know it is slightly different than with the UNO.
Questions I have include:
How do you indicate you want to talk to a slave on pin 4? Instead of digitalWrite(4,LOW) do you call SPI.begin(4)? etc..

Can someone post some example code?

Everything you need is given here - you just need to know how to put it together:

https://www.arduino.cc/en/Reference/DueExtendedSPI

There are variants of all the major methods that take an extra parameter - that parameter is the first parameter in the parameter list and defines the SS Pin to use for that function.  That includes the .transfer() function.

To use it you have to begin() all the pins you want to use SPI with. Then you can use .transfer() with those pins:

void setup() {
    SPI.begin(10);
    SPI.begin(4);
}

void loop() {
    // Receive using pin 10 as SS
    byte byteFromTen = SPI.transfer(10, 0x00);
    // Transmit 123 using pin 10 as SS
    SPI.transfer(10, 123);
    // Both directions:
    byte otherByteFromTen = SPI.transfer(10, 123);

    // Receive using pin 4 as SS
    byte byteFromFour = SPI.transfer(4, 0x00);
    // Transmit 123 using pin 4 as SS
    SPI.transfer(4, 123);
    // Both directions:
    byte otherByteFromTen = SPI.transfer(4, 123);
}

Doing multi-byte transfers is slightly more complex since you don't have control over the SS pin, so you have to use yet another version of the transfer() function that tells it to "continue" the transaction:

// Receiving 3 bytes using pin 4:
byte firstByte = SPI.transfer(4, 0x00, SPI_CONTINUE);
byte secondByte = SPI.transfer(4, 0x00, SPI_CONTINUE);
byte thirdByte = SPI.transfer(4, 0x00);

Of course, mixing reading and writing is pretty much the same as usual. For instance, to read the port A values from an MCP23S17 would look like:

SPI.transfer(4, 0x41, SPI_CONTINUE); // Address 0, read bit set
SPI.transfer(4, 0x12, SPI_CONTINUE); // Select register 0x12 (GPIOA)
byte porta = SPI.transfer(4, 0x00);

The SPI_CONTINUE tells the SPI system to keep the SS pin LOW. It is only then raised once it gets a .transfer() without the SPI_CONTINUE. This is the same as the traditional way of using digitalWrite() to lower SS before the first transfer and raise it after the last transfer.


Drive a 12V pump do I need a l293 driver Me and my girlfriend are working on a small automatic plant watering system. Our first goal is to make an electrical 12V pump suck water out of a bottle.

As we were reading tutorials online we noticed that many people hook up a driver such as the l293 to their arduino in order to control the pump (essentially a brushed DC motor).

http://www.ti.com/lit/ds/symlink/l293.pdf

Our pump is 12V 4.2 W.

My question is do we really need a driver like that for just activating / deactivating the pump ?

In my understanding the driver offers an H-bridge setup allowing to control up to two motors in both directions.

Are there any other reasons to prefer this driver instead of a simple MOSFET / Transistor setup with such a simple use case like ours ?

Thank you for your help.

Best regards

Unless you wish to reverse the direction of the pump without reconnecting the wires in the opposite way, there is no need for a L293. A MOSFET that operates as a switch should be sufficient in your case. You can also try to PWM it and reduce/control the water flow.


How many and fast interrupt pin can handle in Uno? So I am using Arduino UNO to do phase cutting and read Fan RPM.

For phase cutting, every half frequency it will triggers interrupts and then arduino will triggers TRIAC. Half frequency(50Hz) is 20ms. And for reading rpm, my fan running at 950rpm or 15.83rps, or doing a revolution for 63ms.

I think both of that works is doing a fast work, and I am afraid if I do it simultaneously the arduino will get an error(like a skip on one half wave, or a skip on reading one revolution), or will it not? Thanks.

You can find the number of external interrupt and pcint pins from the data sheet.

If you use interrupts, the overhead is about 20 or so ticks, or just over 1us. That gives you the minimum.

If polling, and you are lucky, 1 tick is all it takes. 1 /16th of a us.


How can I power an ESP8266 using a 9V 1A barrel connector power supply? I have a Huzzah Feather ESP8266 (pinout) and due to the requirements of my project, I need to supply it with a 9V power adapter with a barrel connector, such as this one.  I'm REALLY new to all of this, so I am trying to figure out how to do this and understand reading dev board specs.

It looks like this development board has a regulator that will adjust a power source down to the appropriate voltage...  but how do I know what parameters it allows?

If I'm understanding correctly, on the pinout sheet above it looks like I would connect a power supply to the "VBUS" and "GND" (right?) pins.  It also says "500mA Max", so does that mean a 1A power supply won't work?  Also, why wouldn't it specify a maximum voltage?

If just connecting a barrel connector to those pins will not work, what am I missing that would get me there?

You cannot. If you look at the datasheet:

https://cdn-learn.adafruit.com/downloads/pdf/adafruit-feather-huzzah-esp8266.pdf

you can read all details on page 25/26:

  Alternative Power Options

  The two primary ways for powering a feather are a 3.7/4.2V LiPo
  battery plugged into the JST portor a USB power cable.

  If you need other ways to power the Feather, here's what we recommend:

  For permanent installations, a 5V 1A USB wall adapter (https://adafru.it/duP) will let you plug in a USB cable for reliable
  power
  For mobile use, where you don't want a LiPoly, use a USB battery pack! (https://adafru.it/e2q)
  If you have a higher voltage power supply, use a 5V buck converter (https://adafru.it/DHs) and wire it to a USB cable's 5V and GND input
  (https://adafru.it/DHu)

  Here's what you cannot do:

  Do not use alkaline or NiMH batteries and connect to the battery port - this will destroy the LiPoly charger and there's no way to
  disable the charger
  Do not use 7.4V RC batteries on the battery port - this will destroy the board

  The Feather is not designed for external power supplies - this is a
  design decision to make the board compact and low cost. It is not
  recommended, but technically possible:

  Connect an external 3.3V power supply to the 3V and GND pins. Not recommended, this may cause unexpected behavior and the EN pin will no
  longer. Also this doesn't provide power on BAT or USB and some
  Feathers/Wings use those pins for high current usages. You may end up
  damaging your Feather.
  Connect an external 5V power supply to the USB and GND pins. Not recommended, this may cause unexpected behavior when plugging in the
  USB port because you will be back-powering the USB port, which could
  confuse or damage your computer.


Can I get around extremely long time to setup WIFI connection WPA2 Personal? I'm using the Arduino Wifi Nina Library to connect an Arduino Uno Wifi Rev2 to wifi and then using the Arduino HTTP Client library to make HTTP post calls to the internet.

To connect the Arduino to my home Wifi Network (WPA2 Personal), I use the WiFi.begin() method. This method takes an excruciatingly long 4 seconds to connect to the Wifi. This seems to be a known issue. Since this methods is synchronous/blocking, my sketch is completely unresponsive during this time to any user input such as button-presses etc. I'm trying to create a proof-of-concept for a commercial-grade product. So having it go unresponsive to user-input for several seconds is unacceptable.

Is there any workaround to this? Is there a asynchronous library to achieve the same goal? Is there some other workaround? How do other people deal with this situation?

4 even 5 seconds is normal for connecting to WiFi. How long takes your phone or other devices to connect?

You can connect a little faster with static IP address.

EDIT: With WiFiNINA library for Uno WiFi Rev.2, you can change the connection timeout with WiFi.setTimeout(). The default is 5 seconds. WiFi.begin() can end with WL_CONNECT_FAILED but if you later check the status of the connection it will eventually be connected.

With esp8266 or esp32 you can make the connection persistent and it is build up immediately after boot and asynchronously. WiFiNINA library doesn't make this possible yet. Some future version will offer WiFi provisioning.


Reset an Arduino Uno in code Is it possible to reset an Arduino (i.e., to reboot it) from code (i.e from the sketch itself)? I know that is possible with a special circuit but is there a chance to make it just with code?

Below is my code and the comment //reset is where I want to force a reset.

#include <TrueRandom.h>

int i;
int randSeed;
long randNumber;

void setup(){
  Serial.begin(9600);
  Serial.println("20 pseudo Zufallszahlen:");
  for (i=1;i<=20;i++) Serial.print(random(10));
  Serial.println();
  Serial.println();
  //randomSeed(TrueRandom.random());
  randSeed = analogRead (A0);
  randomSeed(randSeed);
  Serial.print("Der 'seed' Wert: ");
  Serial.println(randSeed);
  Serial.println();
  Serial.println("20 Zufallszahlen mit analogem 'seed' Wert:");
  for (i=1;i<=20;i++) Serial.print(random(10));
  Serial.println();
  Serial.println("---------------------------");
  Serial.println();
  delay(500);
  //reset
}

void loop() {
}

I want to reset the micro-controller at the end of the setup function to show the effect of random numbers with and without a seed.

There three ways to accomplish this. (last is my favorite)

1) Jumper an unused IO to the RESET pin. Leave it as INPUT for normal
    run, As it is externally pulled high. And when desired to reset set
    it as LOW and Output. (bang its rebooting).

setup() {
  ...
  pinMode(PINtoRESET, INPUT);    // Just to be clear, as default is INPUT. Not really needed.
  digitalWrite(PINtoRESET, LOW); // Prime it, but does not actually set output.
  ...                            // Does disable 10K pull Up, but who cares.

then when desired...

...
  pinMode(PINtoRESET, OUTPUT);   // lights out. Assuming it is jumper-ed correctly.
  while(1);                      // never gets here.

2) Jump to beginning of the code.

void(* resetFunc) (void) = 0;  // declare reset fuction at address 0
...
resetFunc(); //call reset

But be careful, this does not perform a true reset, in that all the registers ARE NOT DEFAULTED. Rather they and the IO are left as is. Where somethings from the bootloader and then the heap will be initialized. And reset are not!

3) Use the watchdog. The SoftReset library makes it easy. Although it is not difficult to implement directly. Shown below..

#include <avr/wdt.h>
...
setup() {
  ...
  MCUSR = 0;  // clear out any flags of prior resets.
  ...

then when desired...

...
wdt_enable(WDTO_15MS); // turn on the WatchDog and don't stroke it.
for(;;) {
  // do nothing and wait for the eventual...
}
...


How to get arduino to always be connected as /dev/ttyUSB0 and with chmod 0777? I've got Debian 10 as OS and for a Project, I need my arduino to always be connected as /dev/ttyUSB0, not any other ttyUSB-number, and I need it to be connected with the 0777 rights for a script to work.
I've read some things about udev, but nothing I tried yet worked.
I tried creating
/etc/udev/rules.d/51-my_usb_device
with the content
SUBSYSTEM=="tty", MODE="0777", KERNELS=="ttyUSB0"
but it does not work, even after reboot (like nothing changed). I must admit though that I do not really understand udev.
How to do this?

Have you considered not trying to force ttyUSB0 but instead creating a symlink to whatever tty is assigned? Your software then just uses the symlink.
A problem with forcing a particular tty is what if you boot without the Arduino but another device is attached? You then need to convince the other device to skip ttyUSB0.
If you would consider a symlink then something like:
ACTION=="add", KERNEL=="ttyUSB*", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="7523", SYMLINK+="arduino"

might get you started. Check the VID and PID using lsusb or similar. To set permissions as well you can use e.g. MODE="0777" as you already have.
There is an example at https://wiki.debian.org/udev that might give more background.


My LED toggeling doesn't work the way I want I want to do LED toggeling so I wrote this:

int led=13, button=12;

void setup()
{
    // put your setup code here, to run once:
    pinMode(led,OUTPUT);
    pinMode(button,INPUT);
}

void loop()
{
    // put your main code here, to run repeatedly:
    if(digitalRead(button)==HIGH && digitalRead(led)==LOW)
    {
        digitalWrite(led,HIGH);
    }

    if(digitalRead(button)==HIGH && digitalRead(led)==HIGH)
    {
        digitalWrite(led,LOW);
    }
}

But It doesn't work well, sometimes I need to press the button many times in order to turn on or of...and some times with just one press.

I saw this video but I didn't understand it well:
https://www.youtube.com/watch?v=aMato4olzi8&t=415s

Anyway I don't know why my way doesn't work well.

There are a few problems with your approach.

You seem to have the button backwards.  You should wire a button so that it is between the pin and ground.  This way it should read LOW when pressed, not HIGH.  It should also have pinMode(pin, INPUT_PULLUP) instead of INPUT.  With the button wired the way you have it to read HIGH then you will need an extra resistor for each button.  With it wired the right way where it reads LOW then it needs nothing extra.
If the first if statement is true and the button is pressed and it turns on the led, what do you think are the chances that you are fast enough to get your finger off the button in the 62.5 nanoseconds it takes to get to that next if statement?   It's not going to happen, so the button is still pressed there and now the led is on so this line turns it right back off.  Only in the rare case where you happen to get your finger off the button at just the right instant will the led stay lit.  To solve this, look at the "State Change Example" that comes with the IDE.  It shows how to keep track of the last state of the button in a variable so you can act only once when the button actually changes state.
Once you get that worked out you will notice that it seems like for every time you press your button it registers tens of presses.  This is switch bounce.  That's a term you should google.  The contacts are making and breaking contact really fast in the in-between pushed and not-pushed state.  But you need to get the first two issues solved before you worry about bounce.


What is the wiring of arduino motor shield to Nano? I have the basic version of the stepper motor driver and a Nano, I see the pins are set to plug directly in to a Uno or similar Arduino, but according to the documentation it just needs most of the digital pins connected to the arduino - https://learn.adafruit.com/adafruit-motor-shield/faq

As it seems they are the opposite position to plug into a breadboard for testing, I may need to wire and solder them (11 to D11, 3 to D3, 5 to D5, 6 to D6). Is this correct or does the Nano not have the power/amperage/timing or something to run this type of shield, hence the lack of compatibility listed for that shield?

I believe, though it's not clear, that the shield in question uses a 74HC595 shift register to control the main motor drivers - the other pins are for the servo interfaces (and they are just wired 1:1). Theoretically you can therefore use any pins you like to control the motor drivers themselves.

It's not the same as the Adafruit one which looks to use direct Arduino control of the motor drivers.


Output voltage range between 0-5v I am using arduino Uno/Mega.
I am trying to output a range of 0-5v volts using PWM.
Is it possible to do it?
It’s would be nice to see some code or instructions, as far I have seen, they used external Module to get that voltage range, maybe I am wrong or I didn’t understand them well.
Thanks!

Short answer: No.
Arduino Unos and Megas have PWM (Pulse Width Modulation) output, which rapidly turn the output on and off with a varying "duty cycle" (The ratio of on time to off time.) That is not the same thing as an analog output voltage.
If you have a constant load you can build a low pass filter that will smooth the output to a slightly dirty DC output based on the PWM output.
You're better off using an external DAC (Digital to Analog Converter.) You send that a digital value and it converts it to a clean, filtered analog output. Most modern DACs are fast enough to output complex waveforms like music.
Edit:
The Arduino zero apparently has a built-in DAC with up to 10-bit resolution. you could use that to output a low current DC voltage. However the zero is a 3.3V device.


Send information (such as a string) over digital pins I wan't to send information from my arduino digital pins to another arduino's digital pins like a string, or a char. Can I do this without something like Software Serial?

The reason I am asking is because I am wanting to send information from several serial devices to my raspberry pi from an arduino. Thing is, that Raspberry pi only has one set of UART pins, so I was thinking because I have extra arduino uno's, why not send then information to the arduino and have it write the received information to the raspberry pi's digital pins..

Now that I am writing this, I think I will connect the 2 arduinos via a serial connection, and use software serial to write out to the raspberry pi, in three different stages, to get the information to the pi.

The reason I am using the PI is I want to display this information on a large screen with many different options, in short the GPU capabilities are what I am using the PI for, that and Processing.

Question still stands though, can you send information over digital pins?

The RaspberryPi is a fairly complete linux computer.  As such it can be a USB Host to many USB Devices.  If you need more serial ports simply buy FTDI equipped USB to serial cables, plug them into a USB hub and plug that into the RaspberryPi.


How much low analog voltage can Arduino uno read? Today I was playing around with arduino analog voltage ranges, the error in output
 with respect to a digital multimeter started to happen when the reading was around 0.0014volts. How much low an arduino can read?

The Arduino Uno uses a processor containing a 10 bit ADC.  This means the ADC can resolve (if we do not consider noise) 2 to the 10th or 1024 voltage levels between zero and the voltage supplied to the Arduino Uno at the AREF pin.  There is a good explanation of the AREF pin in this stackexchange.com question / answer.  It is common practice to supply the AREF with voltages lower than the positive rail the processor is operating at to improve resolution of expected lower voltages.  For example, if you do not expect to measure voltages higher than 3.3 volts on a 5 volt Arduino, use the 3.3 volt supply as a reference.  Relative to using a 5 volt reference, using a 3.3 volt reference decreases your granularity from 0.00489 to 0.00322 volts per step.

Of course there is a lot of noise in most ADC circuits.  Finding the average of many ADC readings helps mitigate this problem.  Consider using exponential averaging.


Why is my esp8266 still visible under "available connections" when connecting to WiFi? I wrote a "Hello world" type of sketch using the Arduino IDE and uploaded it to an esp8266. I used no libraries, or any kind of WiFi commands. However, when I powered up the esp8266, it was visible under "available connections" when I connected to WiFi using a Windows laptop. I was told that the firmware on an esp8266 (which has the AT commands) is being flashed when the Arduino IDE uploads a sketch. Why do I still see the esp8266 when my laptop connects to WiFi?

It's because you don't actively program the WiFi - you just give instructions to configure it, and those instructions are stored elsewhere in flash, separate to a sketch.  The WiFi code is always included and always running regardless of what you include or don't include in your sketch.

Uploading a sketch doesn't replace those settings, and so they remain.

To change the settings you will need to write a sketch that specifically changes them - maybe set it to STA mode, for example.

If you want to completely blank the ESP8266, including the WiFi settings, there is an option in the Tools  menu in the IDE to Erase Flash.


Cannot understand why this code work but this not I've done a simple aurduino sketch, I have this code, and this don't work:

#define voltageInput A0
int qntR;
float mr;
float qr;
float Distanza;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(voltageInput,INPUT);
  mr=(130-20)/float(1023-205);
  qr=20-mr*205;
  Serial.print(mr,4);
}

void loop() {
  // put your main code here, to run repeatedly:
  qntR=analogRead(voltageInput);
  Distanza=mr*qntR+qr;
  Serial.print("Distanza: ");
  Serial.print(Distanza);
  Serial.print(" cm");
  Serial.println("");
}

And the I have this code:

#define voltageInput A0
int qntR;
float mr;
float qr;
float Distanza;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(voltageInput,INPUT);
  mr=(130-20)/(1023-205);
  qr=20-mr*205;
  Serial.print(mr,4);
}

void loop() {
  // put your main code here, to run repeatedly:
  qntR=analogRead(voltageInput);
  Distanza=mr*qntR+qr;
  Serial.print("Distanza: ");
  Serial.print(Distanza);
  Serial.print(" cm");
  Serial.println("");
}

In which I have delete the float from mr=(130-20)/float(1023-205);,and if I delete the float the code stop working (mr is always equal to 0), why?

Your problem is that you are doing integer maths.

mr = (130-20)/(1023-205)

reduces to:

mr = 110/818

Which normally equates to:

mr = 0.135

But since all those numbers are integers the result is an integer, and is truncated at the decimal point, which means that mr is assigned:

mr = 0

You can force floating point maths by either including a decimal point in one of the numbers, or adding the suffux f:

mr = (130-20)/(1023-205.0)

or

mr = (130-20)/(1023-205f)

Or casting a portion of the sum to a float as your other code does.


Arduino, lcd 16x2 and UTP cable shows gibberish text? I'm using an arduino uno, and an 16x2 LCD that is connected to the arduino uno with a 1m long UTP cable to transmit data and as well power the LCD screen.

I used to test my code and my wiring with short wires and everything worked perfectly, as soon as I used the UTP cable to move my lcd a bit away from the arduino, the same code and wiring doesn't work, all i see is gibberish text (nonsense characters on the screen).
I have other components in the circuit, but I have disabled them all and checked again (quadruplechecked) everything, including the LCD alone, but the problem remians. I also gave the lcd a whole separate powering line, as I thought it could have run low in energy bcs of other components using the same 5v line.

Anyone has any idea of what could the problem be? Has anyone tried connecting components with UTP cables? Should I maybe use STP instead?

Thanks!

Is the cable shielded?
Have to performed continuity test on all leads of the cable to ensure there no break internally that could be causing an issue, or a short?

What is the impedance of your total length of cable?

These sorts of checks will help you further narrow down the issue. If you are certain your wiring is correct, then the most probable issue is either a hardware failure (continuity test)
a hardware limitation (Too much resistance for accurate data travel)
Improper Hardware, unshielded wires can be subject to crosstalk, or signal corruption/distortion due to external signals interfering.


Arduino program does not start when plugged in I am having trouble with my Arduino Mega with getting the program to start when the Arduino is plugged into a computer via USB.  All that happens is the LED turns on and stays on.  The device does not initialize, and only when I press the reset button does it begin the setup.  How can I make the Arduino start the program when it is first plugged into the computer?

EDIT: my code

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

void loop() {
  Serial.println("test");
}

very simple, which is why i don't understand why this is happening

I would recommend you to follow the following instructions step by step to verify your Arduino Mega.

Reboot your computer
Connect the Arduino using the USB cable to PC and check the Arduino itself if there is any jumper wires connected/grounded. If there are then remove them all.
Upload a blank sketch first. Go to File -> New
Verify the Arduino has accepted the blank sketch and resetted.
Upload the Blink sketch from the File -> Examples -> 0.1Basics -> Blink
Verify if the Pin 13/onboard LED is blinking. If yes then go to uploading your sketch, if no then there is a hardware/bootloader problem with your Arduino. Watch this video on how to burn bootloader here. https://www.youtube.com/watch?v=X5achE10rCI


How to wire up and trigger this SPDT relay? How do I connect a SPDT relay to an Arduino?

It's a DC 5V Coil 6 Pin relay and ultimately what I want to do is have the Arduino trigger the relay to allow voltage to pass through.

I couldn't find a data sheet, but apparently this is the layout...

----------------------------------
|....1......2..............3.....|
|................................|
|....4......5..............6.....|
----------------------------------

2 and 5 are the 5v relay coil
3 and 6 are shorted together
3 and 1 are normally closed
3 and 4 are normally open

You can use this connection diagram with your relay

6 pin Relay pin out

Code

int Relay = 8;

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

void loop()
{
      digitalWrite(Relay, HIGH);  // turn on relay
      delay(2000);
      digitalWrite(Relay, LOW);   // turn off relay
      delay(2000);
}

First check your relay with multi meter then find the Coil, Com, NO and NC points for correct connection.
Hope this will help you.


Start program on PC using Arduino I want to create arduino sketch that start program on my computer (i.e., browser) when I push button on Arduino itself.

Is it possible to make it using Arduino uno? I already know how to make a serial connection between PC and Arduino and use Processing software, but as I know, Processing cannot interact with another programs.

Processing is just Java.  If Java can do it Processing can do it.

And Java can do it.

Just ask Google about the Java ProcessBuilder class.


Put ATmega328 in very deep sleep and listen to serial? I have investigated the sleeps options of the ATmega328, and read a few articles about it, and I would like to understand if there are more options.

So I would like to get as low current as possible, so that anything less that 100uA would be good - as long as I can listen to uart and interrupts for waking up.

I am using a custom PCB (not the UNO), with ATmega328p.

Setting the chip to deep sleep:

 set_sleep_mode (SLEEP_MODE_PWR_DOWN);
 sleep_enable();
 sleep_cpu ();

would not wake it up with serial communication,according to this.

You will need to put it in IDLE mode, to listen to serial, but this would consume a few mA -bad.

I have found this link where you can connect in hardware the serial to the interrupt - which is dangerous so you can loose data, and moreover, I need these 2 interrupts pins.

I also read this article of Gammon, where you can disable some things, so you can get IDLE sleep with much lower power - but he didn't mention how exactly you get from this:

 power_adc_disable();
      power_spi_disable();
      power_timer0_disable();
      power_timer1_disable();
      power_timer2_disable();
      power_twi_disable();

So, bottom line, is there any option out there, to get less than 0.25mA at least, and also listen to serial port, without any hardware manipulation?
For example, waking up with long serial data input?

A board we make does this.

The RX pin is wired to INT0
INT0 pin set to input or input pullup depending on how the RX line is driven
On sleep, INT0 low level interrupt is enabled

//Clear software flag for rx interrupt
rx_interrupt_flag = 0;
//Clear hardware flag for rx interrupt
EIFR = _BV(INTF0);
//Re-attach interrupt 0
attachInterrupt(INT_RX, rx_interrupt, HIGH);

INT0 interrupt service routine sets a flag and disables the interrupt

void rx_interrupt()
{
    detachInterrupt(INT_RX);
    rx_interrupt_flag = 1;
}

On wakeup, we check for the flag (there are other interrupt sources)

On the comms side of things we use a message protocol that has a start character > and end character \r. e.g. >setrtc,2015,07,05,20,58,09\r. This give some basic protection against losing messages, as incoming characters are not processed until a > is received. To wake up the device we send a dummy message before transmission. A single character would do it, but we send >wakeup\r hehe.

The device stays awake for 30 seconds after the last message is received in case of new messages. If a new message is receive the 30 second timer is reset. The PC interface software sends a dummy message every second to keep the device awake while the user has it connected for configuration etc.

This method gives absolutely no problems at all. The board with a few peripherals uses about 40uA when sleeping. The actual current consumed by the ATMega328P is probably around 4uA.

Update

At look at the datasheet shows that the RX pin is also pin change interrupt pin 16 (PCINT16)

Thus another method without wires may be

Before sleep: Set the port change interrupt mask bit in PCMSK2 for PCINT16, clear the pin change port 2 flag in PCIFR, enable the pin change port 2 interrupt (PCINT16-PCINT23) by setting PCIE2 in PCICR.
Setup an ISR for the pin change port 2 interrupt and continue as before.

The only caveat with the port change interrupt is that the interrupt is shared across all the 8 pins that are enabled for that port. So if you have more than one pin change enabled for the port, you have to determine which triggered the interrupt in the ISR. This is not a problem if you are not using any other pin change interrupts on that port (PCINT16-PCINT23 in this case)

Ideally this is how I would have designed our board but what we have works.


Arduino Uno Constantly Resets with WiFi and 4 Relay Module I am using an Arduino Uno with a 4 relay module (found here: http://www.amazon.com/JBtek-Channel-Module-Arduino-Raspberry/dp/B00KTEN3TM?ie=UTF8&psc=1&redirect=true&ref_=oh_aui_detailpage_o04_s00) and an Adafruit CC3000 WiFi breakout board.  However, once I connect the power source, the board just constantly cycles on and off, e.g. about 1 second per cycle.  Could this have to do with too much current being drawn? Or that the current output of the digital pins isn't enough for all of the relay inputs? I'm new with this, but I am sure all of the pins are appropriately connected.

EDIT: If I use the USB connector (5V 1A) instead of the external power supply, I can connect 1 or 2 of the relays without problem, but must do so AFTER the wifi has already connected to the network, otherwise the wifi chip will never connect.  Also, if I toggle the relays a few times, the wifi becomes unresponsive.  I suspect a current issue maybe?. Any ideas? Thanks!

It Will be a power issue you need to supply power direct to the relay modules VCC independent of the arduino, ensure the earths are connected and just use the digital outputs from the arduino to control the relays. Digital low normally switches the corresponding relay on.


Trying to communicate with an ESP8266 G'day guys, I'm trying to get an ESP8266 to work with an Arduino Uno.Here is the wiring.

When I go to the serial monitor (115200 baud) and type: AT, there is not response from the ESP8266.Is there something that I am missing?I also have a servo motor connected, it works fine.

include "Arduino.h"
include "ESP8266.h"
include "dweet.h"
include "Servo.h"

define ESP8266_PIN_RX 10
define ESP8266_PIN_TX 11
define SERVO9G_PIN_SIG 2

const int servo9gRestPosition   = 20;
const int servo9gTargetPosition = 150;
const char *SSID     = "Wireless Network";
const char *PASSWORD = "wireless_password";

ESP8266 wifi(ESP8266_PIN_RX,ESP8266_PIN_TX);
Servo servo9g;

const int timeout = 10000;
char menuOption = 0;
long time0;

void setup()
{
   Serial.begin(9600);
   while (!Serial); //await connection.
   Serial.println("start");

   wifi.init(SSID, PASSWORD);
   servo9g.attach(SERVO9G_PIN_SIG);
   servo9g.write(servo9gRestPosition);
   delay(100);
   servo9g.detach();

}

void loop()
{
   servo9g.attach(SERVO9G_PIN_SIG);
   servo9g.write(servo9gTargetPosition);
   delay(500);
   servo9g.write(servo9gRestPosition);
   delay(500);
   servo9g.detach();
}

I'm using the ESP8266 Library.When trying to connect it just says Initializing device...

Unless you have some project constraints which make it mandatory to use naked ESP8266, why not use a NodeMCU to communicate with the Arduino in a master/slave relation over I2C?

#include <Wire.h>
#define I2CAddressESPWifi 8

in setup()

Wire.begin(D1,D2); // SCL D1 SDA D2

then call from anywhere inside your loop() call this function

char readSlave(int x) { // send current time
  String xY = String(x);
  char c;
  int charArrayLength = xY.length()+1;
  char bufferChar[charArrayLength];
  Wire.beginTransmission(8);
  xY.toCharArray(bufferChar, charArrayLength);
  Wire.write(bufferChar);
  Wire.endTransmission();
  delay(10);
  Serial.print("wire sent: [");
  Serial.print(x);
  delay(50);//Wait for Slave to calculate response.
  int counter = 0;
  char buffMe[32];
  int bytesIn = Wire.requestFrom(8,32);
  while (Wire.available()) {
    delay(2);
    buffMe[counter] = Wire.read();
    /*
    c = Wire.read();
    Serial.print(c);
    */
    counter++;
  }
  delay(10);
  Wire.endTransmission();
  delay(500);
  Serial.print("] bytesIn: [");
  Serial.print(bytesIn);
  Serial.print("] buffMe: [");
  Serial.print(buffMe);
  Serial.print("]");
  return buffMe;
}

and your arduino will be waiting (setup)

Serial.begin(9600);
// slave listens for call from master NodeMCU
Wire.begin(I2CAddressESPWifi);  // predefined as `8` or whatever address you choose
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);

and at the end of your code

void receiveEvent(int howMany) {
  if (howMany) {
    Serial.print("bytes[");
    Serial.print(howMany);
    Serial.print("] Received[");
    char charIn[howMany];
    int counter = 0;
    while (Wire.available()) {
      char c = Wire.read();
      charIn[counter] = c;
      //Serial.print(c);
      counter++;
    }
    delay(10);
    //do something with command from master
  }
}
void requestEvent() {
  char bufferChar[20] = "slave answer string";  // automatically null terminated extra character at end
  Serial.println(bufferChar);
  Wire.write(bufferChar);
}


Different voltage sources across Vin and DC jack So I understand that the USB VBUS circuitry turns off provided there is a high enough vin voltage using the PFET and comparator.

I can see that the DC jack is connected to the Vin pin via a diode.
However, what is to stop someone from plugging a voltage source across the Vin and at the same time putting across a voltage on the DC jack.

If I incorrectly plugged in a voltage source of a low voltage like a coin cell battery across the VIN pin and also powered the device using the 9 V DC jack, wouldn't that then send current through the VIN pin and back to the coin cell battery?

Is that what would happen in this instance? And if so then shouldn't there be a design feature to prevent users from damaging it like that? Fool/fail safe?

wouldnt that then send current through the Vin pin and back to the coin cell battery? Is that what would happen in this instance?

Yep, that's right.

  shouldn't there be a design feature to prevent users from damaging it like that? Fool/fail safe?

No. VIN can also be VOUT. You can use it to power other things that want a higher voltage.


Read data from arduino once only serial communications (jSSC) I am trying to get the UID of RFID from Arduino to netbeans. I was able to display it to a textfield, but once another rfid was scanned, it is displayed together with the UID from the prev scan. How do I stop Arduino to send data so the only thing displayed in the textfield was the first UID scanned.

Here is Arduino code:

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10         // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
    Serial.begin(9600);     // Initialize serial communications with the PC
    while (!Serial);        // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init();     // Init MFRC522

    //mfrc522.PCD_DumpVersionToSerial();    // Show details of PCD - MFRC522 Card Reader details
    //Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

void loop() {
    // Look for new cards
  String code = "";
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }
    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }
  for (byte i = 0; i < mfrc522.uid.size; i++) {
      code += String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" :" ");
      code += String(mfrc522.uid.uidByte[i], HEX);
  }
  code.toUpperCase();
  Serial.println(code);
  mfrc522.PICC_HaltA();
}

Unless there is a fault in the library you are using there is nothing wrong with the Arduino code, this can be seen from the serial output.

The fault is with the receiving java code, pump test data into that to see what is wrong.


Storing IR Sensor value not working This is my first time working on Arduino for my project and I ran into an issue. I'm trying to make a very simple Vending Machine. Coin or any obstacle passes in front of the IR sensor and based on that, the user can either press button 1 or 2 and based on that motor 1 or 2 would run respectively.
The overall logic works exactly how I want it to, the issue I'm facing is that the variable (sensorStatus) storing the IR sensor value isn't working correctly. Whether anything passes in front of it or not, it lets me press the buttons anyways and the motor starts working.
void loop() {

  int sensorStatus;

  //this is where im having the issue
  if (digitalRead(inSensor) == LOW) sensorStatus = LOW;

  if(sensorStatus == LOW) {
      buttonStatus1 = digitalRead(inButton1);

      if(buttonStatus1 == HIGH) {
        digitalWrite(relayControl1_1, LOW);
      } else {
        digitalWrite(relayControl1_1, HIGH);
      }

      buttonStatus2 = digitalRead(inButton2);

      if(buttonStatus2 == HIGH) {
        digitalWrite(relayControl2_1, LOW);
      } else {
        digitalWrite(relayControl2_1, HIGH);
      }

      sensorStatus = HIGH;
   }
}

If I don't use this logic and store the value of the sensor directly into the variable (sensorStatus), the whole program seems to be working till I have an obstacle in front of the sensor continuously. I don't want this to happen, I want it to work in such a way that once an obstacle passes in front of the sensor it keeps the value (even after the obstacle is gone) until a button is pressed and after that, it gets rid of the value to repeat the process once again. It seems to be a code logic issue but I can't seem to figure out the logic behind it.
My Complete Source Code:
const int relayControl1_1 = 13; // relay 1 of 1 (input 1)
const int relayControl1_2 = 12; // relay 1 of 2 (input 2)
const int relayControl2_1 = 11; // relay 2 of 1 (input 3)
const int relayControl2_2 = 10; // relay 2 of 2 (input 4)

const int inButton1 = 9; //input button 1
const int inButton2 = 8; //input button 2

int buttonStatus1 = 0;
int buttonStatus2 = 0;

const int inSensor = 7;

void setup() {
  Serial.begin(9600);
  pinMode(relayControl1_1, OUTPUT);
  pinMode(relayControl1_2, OUTPUT);
  pinMode(relayControl2_1, OUTPUT);
  pinMode(relayControl2_2, OUTPUT);

  pinMode(inButton1, INPUT_PULLUP);
  pinMode(inButton2, INPUT_PULLUP);

  pinMode(inSensor, INPUT_PULLUP);

}

void loop() {

  int sensorStatus;

  //this is where im having the issue
  if (digitalRead(inSensor) == LOW) sensorStatus = LOW;

  if(sensorStatus == LOW) {
      buttonStatus1 = digitalRead(inButton1);

      if(buttonStatus1 == HIGH) {
        digitalWrite(relayControl1_1, LOW);
      } else {
        digitalWrite(relayControl1_1, HIGH);
      }

      buttonStatus2 = digitalRead(inButton2);

      if(buttonStatus2 == HIGH) {
        digitalWrite(relayControl2_1, LOW);
      } else {
        digitalWrite(relayControl2_1, HIGH);
      }

      sensorStatus = HIGH;
   }
}

Thanks to the help from @Majenko♦ I was able to fix the issue.
1 - int sensorStatus; should have been set to static int sensorStatus = HIGH; to make the program remember the value of the sensor.
2 - sensorStatus = HIGH; should have been right after digitalWrite(relayControl1_1, HIGH); in the buttonStatus conditional else part to make the program set the sensorStatus back to HIGH correctly.
3 - Unrelated to the question posted, doing the above steps made the program run the motors continuously unless they were stopped by an obstacle from the IR sensor. This was fixed by adding delay(2000); digitalWrite(relayControl1_1, LOW); after the sensorStatus = HIGH; mentioned in the 2nd step.
Source Code after fixing:
const int relayControl1_2 = 12; // relay 1 of 2 (input 2)
const int relayControl2_1 = 11; // relay 2 of 1 (input 3)
const int relayControl2_2 = 10; // relay 2 of 2 (input 4)

const int inButton1 = 9; //input button 1
const int inButton2 = 8; //input button 2

int buttonStatus1 = 0;
int buttonStatus2 = 0;

const int inSensor = 7;

void setup() {
  Serial.begin(9600);
  pinMode(relayControl1_1, OUTPUT);
  pinMode(relayControl1_2, OUTPUT);
  pinMode(relayControl2_1, OUTPUT);
  pinMode(relayControl2_2, OUTPUT);

  pinMode(inButton1, INPUT_PULLUP);
  pinMode(inButton2, INPUT_PULLUP);

  pinMode(inSensor, INPUT_PULLUP);

}

void loop() {

  static int sensorStatus = HIGH;

  if (digitalRead(inSensor) == LOW) {
    sensorStatus = LOW;
  }

  if(sensorStatus == LOW) {
      buttonStatus1 = digitalRead(inButton1);

      if(buttonStatus1 == HIGH) {
        digitalWrite(relayControl1_1, LOW);
      } else {
        digitalWrite(relayControl1_1, HIGH);
        sensorStatus = HIGH;
        delay(2000);
        digitalWrite(relayControl1_1, LOW);
      }

      buttonStatus2 = digitalRead(inButton2);

      if(buttonStatus2 == HIGH) {
        digitalWrite(relayControl2_1, LOW);
      } else {
        digitalWrite(relayControl2_1, HIGH);
        sensorStatus = HIGH;
        delay(2000);
        digitalWrite(relayControl2_1, LOW);
      }
   }
}


Servos: attach() and write() Arduino newbie here, so this question might sound too simple. I am trying to run a parallax continuous rotation servo using Arduino Uno. From the reference, I learned that the servo needs to be "attached" to one of digital pins with PWM capability, and the servo's speed can be controlled by write(0~180, 90=stop).

But I am having a hard time understanding the role of the PWM digital pin. If the servo's speed and direction of rotation is determined by write(), what is the role of attach(pin#)?

Thanks in advance!

attach tells the servo library which pin it should be writing to, this is stored somewhere in ram and write will look it up and communicate with the correct pin.

It's possible that you are using the other pwm capable pins for other purposes and suddenly having that library interfere with that is not a good thing.


What type of Arduino is this? I found a bunch of Arduinos (seemingly), but I can't identify the type.

I first thought of a Micro, but the chip is a MEGA328PAU and the Micro should have a MEGA32U4 instead:

I know it's also not a Nano, because the Nano is a bit longer:

Next, I looked up the List of Board Specs. Based on the chip, the following models remain:

Lilypad, can easily be excluded due to its shape
Lilypad SimpleSnap, can easily be excluded due to its shape
Uno, can easily be excluded due to its size
Ethernet, can easily be excluded, because of the Ethernet port
Mini
Pro
Pro Mini

So I am left with Mini, Pro Mini and Pro. The back of the board is not very helpful, since it IMHO misses the markers in the silk sceen:

It definitely looks like the Pro Mini from Arduino Store, but the Arduino store seems not to offer the Mini and Pro, so I don't have a comparison.

What type of Arduino is this? And, if possible, do you have a visual comparison of the three remaining types?

It is a version of Pro Mini.
here in DIY MORE shop

The Mini has regulator. Power it over RAW pin with 7 to 12 V and measure the Vcc pin if it shows 5v or 3.3 V.

To determine the frequency, look at the resonator (the component next to pin 2).

EDIT: the resonator markings are hard to read and very cryptic. to determine the frequency you could install Sparkfun boards package. There you can select the different variants of Pro Mini. Upload Blink. If the upload is successful and it Blinks in 1 second intervals, you have the right setting.


Speedometer slow reaction arduino I'm trying to make a speedometer, with utilization of interrupt for get number of pulse and some calculation for getting speed, but when compute speed the arduino freeze for some second and i lose alot of impulse and false all my successive capture of impulse. Why? thanks for reply

const int contaImpulsi = 2;
volatile int impulsi =  0;
int impulsiOld = 0;
static int appoggio = 0;
unsigned deltaT[3];
unsigned vel = 0;

void setup() {
  Serial.begin(9600);
  attachInterrupt(contaImpulsi, definisciTempi, RISING);
}

void loop() {

  if (impulsiOld == impulsi || impulsi > impulsiOld)
  {
    if (appoggio == 3) {
      deltaT[3] = millis();
      appoggio = 0;
    }
    if (appoggio == 2) {
      //Serial.println("ASSEGNO DELTA T 2");
      deltaT[2] = millis();
      //Serial.println(deltaT[2]);
      appoggio = 3;
    }
    if (appoggio == 1) {
      //Serial.println("ASSEGNO DELTA T 1");
      deltaT[1] = millis();
      appoggio = 2;
    }
    if (appoggio == 0) {
      //Serial.println("ASSEGNO DELTA T 0");
      deltaT[0] = millis();
      appoggio = 1;
    }
  }
  impulsiOld = impulsi;

  if (appoggio == 3) {

    int t1 = (deltaT[1] - deltaT[0]);
    int t2 = (deltaT[2] - deltaT[1]);
    int dividi = t1 + t2;
    vel = (((690 * 2000 / dividi) * 3.6) / 10) * 0.85; // here i think is where the program freeze

    Serial.println("------------------------------------------");
    Serial.print("SPEED: ");
    Serial.println(vel);
    Serial.println("------------------------------------------");
  }
}

void definisciTempi() {
  impulsi++;
}

First off a comment on your variable types. It's not the cause of your problem, but just something to watch for in future:

int impulsi =  0;

This should be voltatile (Edit: I see you updated that, that's ok).

unsigned deltaT[3];
unsigned vel = 0;

These lack a type. As such the default to int. Your deltaT array should be unsigned long since it stores time. It will overflow very rapidly otherwise.

Now on to your problem.

The core of your problem is your methodology of calculating the speed. This bit:

if (impulsiOld == impulsi || impulsi > impulsiOld)
{
  ...
}
impulsiOld = impulsi;

is going to be running pretty much always. That's because impulsiOld and impulsi will either always be the same (since you set them to be the same) or impulsi is going to be greater than impilsiOld since you received a pulse in the brief interlude when it's not running that bit.

And that means that all your deltaT entries are going to be the same most of the time.  Which leads me on to the next bit:

int t1 = (deltaT[1] - deltaT[0]);
int t2 = (deltaT[2] - deltaT[1]);
int dividi = t1 + t2;
vel = (((690 * 2000 / dividi) * 3.6) / 10) * 0.85;

If delatT[1] and deltaT[0] are the same, then t1 will be 0. The same goes for t2. 0 + 0 = 0, so dividi will also be 0.

And that means:

690 * 2000 / 0

Which will be a divide by zero exception and will cause the MCU either to lock up or to reboot. If the latter you will see the bootloader run for a couple of seconds.

There are two normal methods of calculating the speed from pulses, and I am not sure what your method is trying to be.

The simplest one is to just count the number of pulses over a given period. Increment the count in your ISR, and after a second has elapsed (or longer, or shorter, depending on the frequencies you are working with) you reset the count to 0 (after storing it elsewhere) and calculate the speed from that stored count.

The other way is to just take the time between two successive pulses. You can average it, maybe with a rolling (AKA moving) average, or just take the raw value depending on what you are measuring.  This method is a little harder since you need to do more work per pulse.

The two methods differ in critical ways when it comes to outputting the results. The first method will always give you a value every second (or whatever time period you use), but it can't cope with pulses that are further apart than the time period you use. The second method doesn't much care about the time between the pulses, but you can only get a meaningful reading if a pulse arrives, which if that is a while means you get no reading for a while. It's harder to determine "not moving" from that.

Also you should look at the use of critical sections when accessing your impulsi variable outside the interrupt routine. It more than 8 bits, so all access to it will be non-atomic and could be interrupted by the ISR.


Can I use L293D driver as ESC for arduino controlled quadcopter I recently thought that it would be fun to build an arduino quadcopter.

As I did some research I realized that the common L293D motor drivers aren't ever used.

Why is this? Could I still use them in my project?

Bipolar bridge drivers like the L293D, L298, etc have extremely high losses.  They are long out of date and a poor choice compared to modern FET chips even for surface vehicles, let alone something that needs a good power to weight ratio for flight.  Typically if you made a small robot with one and some AA cells, you'd have to have an extra cell in the pack just to cover the losses of the L293D.  An aircraft (and especially a vertical lift one) cannot afford that waste.  Also the wasted energy shows up as heat (though I suppose you could position the chip in the propwash).

Actual quadcopters use MOSFET drivers, typically discrete ones carefully selected for a low RDSon at a low enough threshold voltage to fully turn on when driven by an MCU output.  Either just one N FET per motor for unidirectional control of brushed motors, or H bridges made of an N FET and either a P FET or else an N FETs with special high side driver circuitry for bidirectional control of brushed motors, or similarly as a half-bridge for each of the three leads of a brushless motor.  The MOSFETs may be found either on the main board in a single board quadcopter, or else they may be packaged in modular speed controllers separated from it.

But providing current to drive the motors is the easy part - sequencing brushless motor commutation, and stabilizing a flight platform are the hard parts.

In that regard, an Arduino is a very poor choice as a flight controller.  A literal one means carrying around a lot of extra mass and connectors that aren't really fitting.  A work-alike on a custom board is possible, but most of the open source projects that started that way have long since moved on to other MCUs with more capability.  You do still see ATmega8's within brushless motor drivers though.


How to Specify Array Length during Object Construction within Arduino IDE? I'm working on a group project to involving the creation of an in-house library using the Arduino IDE. As the Arduino IDE uses C++, the library must be a class. One of the classfields is an array of numbers. We would like it if we could specify the array length during object construction, as there are pros and cons to low and high array lengths. Is it possible to specify or change the array length during object construction?

Unfortunately, the Arduino IDE doesn't allow the usage of C++ vectors, so that's out of the question.

Another way is for the caller to provide the memory as a pointer to enough bytes for 'N' objects (cast, if necessary, as a pointer to the required type), and the number, 'N' of such objects. This gives the caller the choice of whether to allocate statically or dynamically.

It looks like you want an array of ints. So you'd allocate an array (statically, in my example, but you could choose whichever best fits your application):

int memArray[N];
// ...
myClass(N, memArray&);

I avoid allocating memory from the heap, but someone else might have a different preference or a situation that requires it; this technique lets the library work for either.


How to make MEMS IR Thermal Sensor - D6T-44-L06 work with Arduino? I am working on project that my team need to detect the presence of the people. At first, we tried with motion sensor but it wasn't the way that we want it to work. We want to detect presence of the people even they don't move.

We decide to go with Omron Thermal Sensor D6T-44-L06. However, there lacking of tutorial or simple code online that actually show how to connect that Omron thermal sensor with Arduino. How can I interface this with Arduino?

Yes should be really easy to implement, as it work like almost all i2c sensor; this manual as also some code example, the chip address, and finally the registry address; that is all you need.
http://www.mouser.com/pdfdocs/D6T01_ThermalIRSensorWhitepaper.pdf


Output 20x20 Image to Arduino serial monitor I am working on an Arduino project where I need to display a black and white (no gray) image to the serial monitor. It doesn't need to be high resolution, so something like 20x20 would work. I will be using this several times a second to make video of a sort, but it doesn't need to be a very high fps (4 or 5 would work). Currently I am just using unicode blocks and printing them (at a baud rate of 500,000) to the serial monitor, but it ends up having a very bad screen tear sort of effect. Is there any way to do this better, or at the very least make the serial monitor print everything at once instead of each character individually?

Thanks!

The Arduino IDE's serial monitor is, to put it bluntly, awful.

Switch to a proper ANSI compatible serial terminal emulator (Tera Term, Putty, Minicom, whatever) and use ANSI control sequences to manipulate the screen.

The simplest ones to use are:

Serial.print("\e[2J"); // Clear the screen
Serial.print("\e[1;1H"); // Move the cursor to coordinate (1,1)

Use the first one to clear the screen in setup(), then use the second one at the start of the loop to move to the top-left corner of the screen (1,1 is top left - the coordinates are given as Y;X not X;Y and start from 1 not 0).

Print your 20 lines of 20 characters as either space (nothing) or your chosen "pixel" character.  The spaces overwrite the existing characters to help reduce flicker (clearing the screen every time would be just awful).

The way serial works (sending one character at a time sequentially) there is no such thing as "All at once". The above is the best you can get without writing your own program to interpret incoming serial data representing an image frame and displaying it.


Wemos: 16x2 display doesn't show anything I connected a 16x2 LCD display to a Arduino Uno. Then I tested a "Hello, Word" code and it works perfect.
Now I want to do the same with a Wemos D1 Mini but it doesn't work.

Here the Wemos is not connected to USB:

This os the "Hello, World" code. I needed to change the name of the pins (maybe this is the problem):

#include <LiquidCrystal.h>

const int rs = 8, en = 7, d4 = D5, d5 = D4, d6 = D3, d7 = D2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  lcd.begin(16, 2);
  lcd.print("hello, world!");
}

void loop() {
  lcd.setCursor(0, 1);
  lcd.print(millis() / 1000);
}

This is the result (potentiometer works perfect):

You are doing it on wemos d1 mini isnt it ?

Then you dint include its header files,
Did you check the "LiquidCrystal.h" has definitions for wemos pinouts?

Your lcd is fine, n wemos too, its just your configuration is wrong.

Check those and update here.


Is there any way I can turn off the 5V pin? I'm trying to find a way I can toggle the 5V pin to turn on/off. I want the voltage to pass to another wire at a certain point. It should be off and then when something happens, the 5V should turn on.

How can I do this?

For energy-efficient switching (along with relatively high-current capability), I recommend using a Darlington transistor connected to one of the output pins (digital for on/off, analogue for variable). Then you would just call  pinMode(A0, OUTPUT); followed by digitalWrite(A0, HIGH); Here is a sketch I made demonstrating what I mean:

Note that a normal transistor would draw more current from the Arduino's pin, which could be bad for the Arduino, and which would waste energy.


L293D to change the direction current and amplify it - Temperature-Stabilizer I have a question about my project. I'm going to make a temperature-stabilizer. To make this, I think I should use a TEC with a H-bridge and a LM35. First of all, I tried to make a H-bridge by myself, I have only used four NPN transistors and It didn't go well. Then I bought L293D motor driver - not the module one, tried it and it works well. But as datasheet says, it's output current is max 600mA. But this current doesn't make TEC work efficiently. So that, I need to amplify the current. But I don't want to buy high amp motor drivers, hardwares are to expensive in my city. Of course I'll if there's no another way.

Arduino will be used to get temperature values from LM35 and give the H-bridge voltage, control the current direction when necessary. I learned how to use transistors to amplify but if I'll change the direction, it won't work. But I don't know how to make this circuit.

The algorithm that I thought using is this:

The scheme that I thought using in this:

What should I do to solve my problem? Thank you for all.

Resources:

My Tec1-12706 Datasheet:
http://www.thermonamic.com/TEC1-12706-English.pdf
LM35 Datasheet - (I have LP package):
https://www.ti.com/lit/ds/symlink/lm35.pdf
L293D Datasheet: https://www.ti.com/lit/ds/symlink/l293.pdf
The transistor method to amplify:
https://www.youtube.com/watch?v=WZD9RZoMhVE

I am interested on this as I have the same issue. What about using a FET or MOSFET to amplify the current that the LM293D provides?


Arduino serial non-blocking I'm writing an Arduino program to communicate with another module using RS485, so I need to control data flow with one pin. But when I set the pin to HIGH (line 88) it almost instantly falls (as you can see in the image, line 70). So my guess is that Arduino Serial.write() function is non-blocking, but I need it to be blocking so the flow control pin stays high during whole packet transmit. Please help. Thank you.

You are right: Serial.write() is non blocking: it puts the data in a
buffer and waits for an interrupt routine to send it through the UART.
If you want to wait for the transmission to complete, you can call
Serial.flush().


Oscillating Analog Readings I am using a JIC 139 UV Sensor (datasheet) with an Arduino Mega 2560 and should be reading smooth curves as I bring a UV source to towards the sensor. Instead, my curves are increasing and oscillating. How can I remove the oscillations and what is the cause of these oscillations?

Code:

float mapfloat(long x, long in_min, long in_max, long out_min, long out_max)
{
    return (float)(x - in_min) * (out_max - out_min) / (float)(in_max - in_min) + out_min;
}

int averageAnalogRead(int pinToRead)
{
    byte numberOfReadings = 8;
    unsigned int runningValue = 0;

    for(int x = 0 ; x < numberOfReadings ; x++)
        runningValue += analogRead(pinToRead);
    runningValue /= numberOfReadings;

    delay(100);

    return(runningValue);
}

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

void loop() {

   float pinRead0 = averageAnalogRead(0);
   float pVolt0 = pinRead0 / 1024.0 * 5.0;

   // In mW/m^2
   Serial.println(pVolt0);
   //  Serial.println(mapfloat(pVolt0, 0.0, 5.0, 0.0, 15.0));

   delay(100);
}

`

Here is a sample screenshot from the Serial Plotter at 3 different distances from the UV Source:

Would post cicuit but don't have enough reputation. Will post as response.
edit: I added a very large capacitor(3300 uf) between the output pin and ground which seemed to smooth the values a little bit but the noise still exists

edit: The x-axis is number of readings and the y-axis is voltage(0-5v) calculated from analogRead()

Without seeing circuit and construction details and oscilloscope traces, it's difficult or impossible to say what the problem is.  It may be due to op amp instability due to a large capacitive load.  It may reflect a beat frequency between some sensor and MCU signals, or aliasing between 60-Hz noise and your data-conversion rate.

Regarding op amp instability, see for example the article Op Amps Driving Capacitive Loads, by Grayson King.  Here is a quote from that article:

  Q. How does capacitive loading affect op amp performance?
  A. To put it simply, it can turn your amplifier into an oscillator. Here's how: [...]

Rather than just connecting that big 3300 μF capacitor to the output pin, perhaps instead try attaching an Active Low Pass Filter to the output, or a unity-gain op amp followed by a Passive Low Pass Filter; etc.  Put big capacitors across power into the UV source and power into the sensor, instead of on the sensor output.

Regarding beat frequencies and aliasing, low-frequency oscillation like that seen in the trace may occur as a difference of two higher-frequency signals, or as a sampling artifact.  To check this out, attach an oscilloscope to the UV source and see if its power consumption oscillates; and/or try a more-rational sampling scheme than that shown in your code.

For example, instead of taking 8 readings within one millisecond in averageAnalogRead() and then waiting 100 ms, perhaps add a delay(1) inside the loop so that readings are spread out slightly more.  Remove the delay(100) from within averageAnalogRead().  Compensate by changing the other delay(100) in loop() to, for example, delay(191) or delay(193).  Try various delay amounts to see if they have an effect on the waveform.


The current direction for digital output pins I am new to Arduino. The digital pins can be configured as output (https://www.arduino.cc/en/Tutorial/DigitalPins) for triggering some sensors. I am now setting a digital (output pin), say no. 7,which is connected to the in1 pin of a SRD relay (https://blog.siliconstraits.vn/relay-what-is-it-and-how-to-use-it/):

I am not very clear about the direction of current flowing in the wire connecting the arduino digital pin to in1. To my understanding, when digitalWrite(pin, HIGH), no current flow into the arduino pin, the relay is not triggered, while digitalWrite(pin, LOW), the current flow into the arduino, and the relay is triggered. Please correct me if I am wrong. Thanks.

When you set a pin to HIGH then that pin will provide 5V.  When you set a pin to LOW then that pin will be set to 0 volts.  Which direction the current flows depends on what is at the other end of the wire.  Current always flows from higher voltage to lower voltage.  If you set a pin to HIGH and the thing it is connected to is at ground then current will flow out of the pin towards ground.  If you set a pin to HIGH but the thing it is connected to is already at 5V then no current flows.  If you set a pin to LOW and the thing it is connected to has some positive voltage then current will flow to the pin.  If you set the pin to HIGH (5V) but the thing it is connected to has more voltage than that (say 10V) then current will flow towards the lower voltage and into the pin, probably damaging the Arduino in the process.


Im trying to get a 3 button password sequence working I'm trying get a password system working that when you click 3 buttons in a certain order (1, 2, 3, 3, 1) then an LED will light up. But as I'm going to implement this into a larger code I can't just have the void loop() going forever to wait for it.

I think my issue is in the while loops and making it wait for one of the buttons to be pressed but I don't know how to get it to work.

thanks

#define greenLED A0
#define redLED A1

int button1 = 5;
int button2 = 4;
int button3 = 3;

void setup() {
  // put your setup code here, to run once:
  pinMode(A0, OUTPUT);
  pinMode(A1, OUTPUT);
  pinMode(button1, INPUT_PULLUP);
  pinMode(button2, INPUT_PULLUP);
  pinMode(button3, INPUT_PULLUP);
}

void loop() {
  // put your main code here, to run repeatedly:
  int total = 0;
  while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
    while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
      while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
        while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
          while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
            if(digitalRead(button1) == HIGH){
              total = total + 1;
            }
          }
          if(digitalRead(button2)==HIGH){
            total = total+1;
          }
        }
        if(digitalRead(button3)==HIGH){
          total = total + 1;
        }
      }
      if(digitalRead(button3)==HIGH){
        total = total+1;
      }
    }
    if(digitalRead(button1) == HIGH){
      total = total+1;
    }
  }
  if(total == 5){
    digitalWrite(A0, HIGH);
    delay(2000);
    digitalWrite(A0, LOW);
  }else{
    digitalWrite(A1, HIGH);
    delay(2000);
    digitalWrite(A1, LOW);
  }
}

Without programming everything out, use something like this:

Initialization:

Create a (global) variable of string ("12331") which is the code
Create a (global) variable of int that shows the number of correct numbers so far (initially 0)

In the while loop:

Check which button is pressed
If it is the correct button
increase the int variable
If that variable is 5 (meaning all numbers ok), light up the LED
Delay
Make the variable 0 again
Clear the LED
If the wrong button is pressed
If it is equal to the first value ('1')

Set the variable to 1 (since the wrong number is the first correct number)

Else

Set the variable to 0


LDC paired with Arduino locks up and freezes. Out of SPRAM? I am making an alarm clock using a 4x20 lcd display, rtc, and Arduino Pro Mini 3.3v. I have implemented a menu system for setting the time/date that blinks the text on the lcd display to indicate that I have it selected, but the blinking randomly stops and the Arduino stops printing to the serial after about ten seconds.

After much head scratching and Googling I came to the conclusion that all my lcd.print() lines were using up all my ram. I tried to create PROGMEM variables to use in the print commands, but I couldn't get it to work so I ended up just adding the F() macro to every print statement (there's a lot). This now prints everything as expected, but the Arduino still freezes up after the same amount of time. Am I using F() wrong or is the problem something else like power???

Visual Studio code says I am using 643/2048 bytes of data/ram and 14960/30720 bytes of flash when I upload the code. (that is with the F() macro implemented)

--------------EDIT----------------

So I've created a small test sketch to use with the same circut, and now I'm really confused. I've been running it for about an hour now and it is still not freezing. The script blinks a full screen of number signs every 200ms. The backlight is on and everything is still powered the same way. This, in theory, rules out both running out of ram and not providing enough power. Any other ideas?

#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <RTClibExtended.h>

LiquidCrystal_I2C lcd(0x27,20,4);
RTC_DS3231 clock;

void setup() {
    Serial.begin (9600);
    lcd.init();
    clock.begin();
    clock.adjust (DateTime (__DATE__, __TIME__));
    lcd.backlight();
}

bool on = true;

void loop() {
    lcd.setCursor (0, 0);

    if (on) {
        for (int i = 0; i < 4; i++) {
            lcd.setCursor (0, i);
            for (int j = 0; j < 20; j++) {
                lcd.print ("#");
            }
        }
    }
    else {
        for (int i = 0; i < 4; i++) {
            lcd.setCursor (0, i);
            for (int j = 0; j < 20; j++) {
                lcd.print (" ");
            }
        }
    }

    on = !on;
    delay (200);
}

I found the problem! it was specific to my code and didn't turn out to have anything to do with ram or power. The problem was I hadn't detached the interrupt from the rtc when I woke it up with a button. It would freeze seemingly randomly because the rtc would fire an interrupt signal when the next minute ticked, while the arduino was awake. I guess it causes problems when you try to interrupt arduino's sleep and it's not actually sleeping. All I had to do was detach both interrupts when the button is clicked. Thank you all for your help :)


Arduino processing serial comunication - losing data? I'm trying to send an array back and forth between Processing and an Arduino UNO. But I think data is being lost along the way. I simply iterate over the array in Processing and send the Values separately. A new set of data is indicated by the character <. On the Arduino the data gets added to a string and sent back for testing.  When I print out the string in processing, some data changed to -1.

The array contains {1,2,3,4,5,6,7,8}

The Output looks like this:

12345678
12345678
1234-1-1-1-1
12345678
12345-1-1-1

Is there something I'm missing in terms of implementation, or is this simply a hardware related problem (like slightly different clock speeds)? Is there any way to improve this?

Arduino Sketch:

int srr[8];

int content; // Data received from the serial port
void setup() {
  Serial.begin(9600); // Start serial communication at 9600 bps
}

 void loop() {
   String str = "val:";
   int test;
   if (Serial.available()){ // If data is available to read,
     content = Serial.read();
   }

   if (content == 60){
     for(int i=0; i<=7; i++)
   {
       str+=Serial.read();
   }
   Serial.println(str);
   }
}

Processing

Serial myPort;  // Create object from Serial class
int arr[]={1,2,3,4,5,6,7,8};  //The array to send

String str;
void setup()
{
  size(200,200); //make our canvas 200 x 200 pixels big
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
}

void draw() {
  //write
  myPort.write("<");
  for (int i =0; i<=7;i++){
    myPort.write(arr[i]);

  }
  //read
  if ( myPort.available() > 0){  // If data is available,
    str = myPort.readStringUntil('\n');         // read it and store it in val
    println(str); //print it out in the console
  }

}

Ok, let's look at your Arduino program a bit at a time (for that is where the problem lies).

if (Serial.available()) { // If data is available to read,
    content = Serial.read();
}

If there is at least one character available in the buffer then read one character into the variable content.

if (content == 60) {

If the variable content is 60 (better to use '>' so you can see what it is), then ...

 for(int i=0; i<=7; i++) {
     str+=Serial.read();
 }

... read 8 characters from the serial buffer whether there are any characters in there or not.

That last bit is the crunch point.  You have an unknown number of characters in the buffer.  You had at least one, and that one you read into content.  You don't then check to see if there are the required 8 more characters available (or wait in each iteration of the loop for each character to actually arrive) before trying to read that character in.

If you take a moment to read the documentation on Serial Read you will see this:

  Returns

  the first byte of incoming serial data available (or -1 if no data is available) - int

The simplest fix is just to make your loop blocking so it waits for a character to arrive before reading it:

for(int i=0; i<=7; i++) {
     while (!Serial.available());  // Wait for a character to arrive
     str+=Serial.read();  // Read it
}


Optimal and Save Water Pump Control I'm using an Arduino Micro, a 12 V water pump and a print relay to water a plant.

A water level switch monitors the the water tank to make sure the water pump does not run dry.

I tried different watering times and figured that when using longer watering times 90,000 milliseconds and longer. The relay sometimes does not switch correctly and the pumps keeps running. I'm not sure if my code is optimal for that kind of purpose:

const int Power_Water = 3; // Pin to turn the Pump On and Off via relay
const int Watering_Time = 90000; // Time the water's supposed to run
const int Water_Tank = 10; // Water Level Switch

void setup() {
  Serial.begin(9600);
  pinMode(Power_Water,OUTPUT); // Pin that triggers the Relay as Output
  pinMode (Water_Tank,INPUT_PULLUP); // Pin of Water_Level Sensor as internal pullup
}

void loop (){
  unsigned long watering_Start = millis();

  while (millis() - watering_Start <= Watering_Time && (digitalRead (Water_Tank) == LOW)){
    digitalWrite(Power_Water,HIGH); // Water Pump goes ON
    Serial.println(millis() - watering_Start);
  }

  if (millis() - watering_Start > Watering_Time || (digitalRead (Water_Tank) == HIGH)){
    Serial.println("Pump OFF");
    digitalWrite(Power_Water,LOW);// Water Pump OFF
  }
  delay(100000000); // example "sleep" time the system is not supposed to water
}

Any suggestions are appreciated.

I changed

const int Power_Water = 3; // Pin to turn the Pump On and Off via relay
const long Watering_Time = 90000; // Time the water's supposed to run
const long Water_Tank = 10; // Water Level Switch

void setup() {
  Serial.begin(9600);
  pinMode(Power_Water,OUTPUT); // Pin that triggers the Relay as Output
  pinMode (Water_Tank,INPUT_PULLUP); // Pin of Water_Level Sensor as internal pullup
}

void loop (){
  unsigned long watering_Start = millis();
  digitalWrite(Power_Water,HIGH);
while (digitalRead(Power_Water) == HIGH){
Serial.println(millis() - watering_Start);
if (millis() - watering_Start > Watering_Time || (digitalRead (Water_Tank) == HIGH)){
    Serial.println("Pump OFF");
    digitalWrite(Power_Water,LOW);
}
}
delay(100000000); // example "sleep" time the system is not supposed to water
}

That delay statement totally defeats the purposes of your millis code.  If you want to enforce a minimum off time then you'll have to do that with millis as well.  Using millis in this way requires that you allow the loop function to repeat many thousands of times per second.  As written you only allow the loop function to run through once every eleven and a half days.


Sending LCD commands to a slave micro I need to split up code which I've already developed for one micro into two different Arduinos connected by serial. The "remote" micro is directly connected to a 20x4 character LCD and the main micro will be sending it a command set to print, move cursor, etc.

My plan was to make functions that used existing code such as
lcd.print("This or that");
to replace the lcd library on the main micro and send command bytes and data bytes up to the remote micro. Seems pretty straightforward.

Then I discovered that apparently lcd.print cannot be a function name. Fine, so I changed it to lcd_print(). So far, so good. But in the existing library, lcd.print accepts strings, bytes, just about anything any length. For example:
lcd_print("any string of any length");
lcd_print(a_2d_array [x] [y]);
lcd_print(this_byte);
lcd_print(this_integer);

Now it's getting over my head. I know I can painstakingly turn a single function into many different functions, but wouldn't it be nice to replicate the functionality of the Arduino LCD library with a single command:

lcd.print();

Then all I have to do is create the function and keep the existing code and send the bytes up to the slave micro. Wouldn't that be nice! I appreciate any thoughts. Thanks.

Just inherit Print class and implement virtual size_t write(uint8_t); and you can use all kinds of print/println that Print implements. See Print Class @arduino.cc.

It implements these methods for you:

size_t print(const __FlashStringHelper *);
size_t print(const String &);
size_t print(const char[]);
size_t print(char);
size_t print(unsigned char, int = DEC);
size_t print(int, int = DEC);
size_t print(unsigned int, int = DEC);
size_t print(long, int = DEC);
size_t print(unsigned long, int = DEC);
size_t print(double, int = 2);
size_t print(const Printable&);

size_t println(const __FlashStringHelper *);
size_t println(const String &s);
size_t println(const char[]);
size_t println(char);
size_t println(unsigned char, int = DEC);
size_t println(int, int = DEC);
size_t println(unsigned int, int = DEC);
size_t println(long, int = DEC);
size_t println(unsigned long, int = DEC);
size_t println(double, int = 2);
size_t println(const Printable&);
size_t println(void);

However you have to implement 2D array print if you really need this, I don't see why do you need it but whatever (you can print each line separately). It just saves you time with implementing everything else.

And for std::ostream like approach I like this (works with anything inherited from Print class):

template <class T> inline Print & operator<<(Print & p, const T & val) {
  p.print(val);
  return p;
}

// ...

void loop() {
  float variableA = 221.23;
  String variableB = "Some string";
  Serial << F("flash string to save some ram: ") << variableA << F(" / ") << variableB << "\n";
}

Then you can implement some commands interface.


Why call a USB connection a serial connection? Does anyone know why Arduino calls a USB connection a serial? When I hear a serial connection I automatically think of a male pin connection and not a USB connection. Also not sure if this a Linux term or just an Arduino thing.

As @ratchetfreak answered, USB is a Serial bus. But there is more.

The microcontroller on Arduino boards has one or more built-in peripherals called UARTs, which stands for Universal Asynchronous Receiver-Transmitter.

This is what the Arduino core calls a Serial port. It uses the same kind of protocol as the old DB-9 serial ports on PCs and such, but at 5V or 3.3V logic levels. Contrast this 0V to 5V voltage swing to indicate Logic LOW and Logic HIGH with the RS-232 standard for the old PC serial ports, which use a +12V to -12V swing to indicate such.

But PCs today don't often have the old RS-232 serial port. They instead have the new USB - Universal Serial Bus - port. On the Arduino board is chip that communicates on one side via USB with the PC and tells the PC that it provides the equivalent of the old COMPORT or /dev/ttyS* serial device; and on the other side via UART with the microcontroller on the Arduino board.

It's like we are "emulating" the old PC serial ports in software over the new USB bus, which itself is a serial communication system, though much more complex than a plain UART.


Code to use an Arduino Mega 2560 to transfer UART  USB to debug an other Microcontroller I have the following circuit and want to use the Arduino Mega 2560 as an debugger for an other Microcontroller.

So I am looking for the code to redirect the UART input from "P17 (RX2)" to the serial USB and the data coming from the serial USB to the output of "P16 (TX2)"

A very simple sketch to pass serial through looks like this:

void setup(){
  Serial1.begin(/*BAUD*/);
  Serial2.begin(/*BAUD*/);
}

void loop(){
  if(Serial1.available()){
    Serial2.print((char)Serial1.read());
  }
  if(Serial2.available()){
    Serial1.print((char)Serial2.read());
  }
}

I would advise both run at the same baud rate, otherwise you may need to do some extra buffering yourself if the arduino starts running out of buffer space. If you want to use the mega's USB connection instead of "Serial1" like your schematic, just switch "Serial1" to "Serial"


Using MouseX in processing to control LEDs. Error in code - LEDs remain off I am fairly new to processing and Arduino - I have a coursework deadline for both on Monday (6th January).

I am trying to write a script that uses the mouseX values to turn LEDs on and off. I haven't got any error messages on either of the scripts but currently, nothing happens to the LEDs (they remain off) when I move my mouse. I have tested the circuit with a simpler Arduino code and it is correct so there must be an error in my code!

I would be very grateful for some help. Thanks!

Processing code:

import processing.serial.*;
Serial port;
byte lightsOn;

void setup()
{
  size(600,300);
  port=new Serial(this,"/dev/cu.usbmodem1411",9600);
}

void draw()
{
  background(32,78,95);
  rect(300,0,300,300);
  noStroke();
  fill(185,215,216);

  lightsOn=byte(mouseX);
  port.write(lightsOn);

  println(lightsOn);
}

Arduino code:

#include <Servo.h>

Servo myservo;
int ledpinA=12;
int ledpinB=13;

void setup()
{
  Serial.begin(9600);
  myservo.attach(ledpinA&&ledpinB);
  pinMode(ledpinA,OUTPUT);
  pinMode(ledpinB,OUTPUT);
}

void loop()
{
  if(0<Serial.available())
  {
    int data = Serial.read();

  if (data>300)
  {
    digitalWrite(ledpinA, HIGH);
    digitalWrite(ledpinB, LOW);
  }
  else
  {
    digitalWrite(ledpinB, HIGH);
    digitalWrite(ledpinA, LOW);
  }
  }
}

lightsOn=byte(mouseX);

A byte can be any number from -128 to 127 (Java has no concept of "unsigned" values). The Arduino will reinterpret that as a value from 0 to 255.

if (data>300)

255, the maximum value, can never be more than 300 - so this will always fail.

You need to re-think what data you are sending and how you want to send it.


Delay between multiple analogReads I'm trying to read 4 analog inputs (1kHz speed). I changed the prescaler to 16 for my Arduino Leonardo according to this link. I then tried to read the analog pins and I used the following code to display the time and the readings:

#define FASTADC 1
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif
double t = 0;
void setup() {
  int start;
  int i;
  #if FASTADC
  // set prescale to 16
  sbi(ADCSRA, ADPS2);
  cbi(ADCSRA, ADPS1);
  cbi(ADCSRA, ADPS0);
  #endif

  Serial.begin(9600);
  Serial.print("ADCTEST: ");
  start = millis();
  for (i = 0 ; i < 1000 ; i++)
    analogRead(0);
  Serial.print(millis() - start);
  Serial.println(" msec (1000 calls)");
}

// the loop routine runs over and over again forever:
void loop() {
  // print out the value you read:
  t = millis() / 1000;
  Serial.print(t);
  Serial.print('\t');
  Serial.print(analogRead(A0)); delay(1);
  Serial.print('\t');
  Serial.print(analogRead(A1)); delay(1);
  Serial.print('\t');
  Serial.print(analogRead(A2)); delay(1);
  Serial.print('\t');
  Serial.println(analogRead(A3)); delay(1);
}

I connected 2V from the DC supply to all the 4 channels and the readings were similar. I used the output from the serial monitor and pasted the readings for 1 sec in Excel to see the frequency. With a 9600 baud rate and no delay between the readings I got 200 Hz (for the 4 analog inputs).

Why is that happening? And is there a relationship between the sampling frequency and the baud rate? Is my way of finding the frequency correct? If not what's the right way?

Finally, I'll be plotting the readings in Matlab, so I guess this will affect the sampling frequency. How can I control it so that I'm sampling with 1kHz rate for all the channels?

Here is the screenshot of the readings from the 4 channels (2V input).

Summarizing everything, I need to know the following:

The effect of adding a delay between every two readings on the accuracy of the readings and the sampling frequency.
How to find the best sampling frequency for every input and how to control it?
Will using Matlab to plot the data affect the sampling frequency?

Thanks.

EDIT: I accepted the answer below, if anyone has the same problem , please make sure that you change the prescaler as I mentioned above for the best results.

At first I thought that the main problem was not that you too slow at sampling, but that you were too slow at transmitting the data. As Edgar already stated, at 9600 b/s you need 22.88ms to send a line, so the maximum frequency is less than 50Hz.

However as you experienced, the speed you are getting is 200Hz. This is because that calculation is right in the case of a real serial interface. Arduino Leonardo, on the other hand, emulates the serial interface. But.. There is no such thing as baud rate. If you look at the CDC emulation source code you will see that the baud rate you pass to the begin function is ignored.

So... Why is it still slow? Because you are using the delay function! You are waiting for 1ms every time you perform an acquisition, and then you still have to perform all the sending. This has two errors embedded: 1) using the delay function breaks the timing - better use a timer - and 2) you are too slow.

Now, if you want a 1kHz sampling (or any delay multiple of 1ms) you already have a timer running (so you can just use that):

#define INTERVAL_LENGTH_US 1000UL

unsigned long previousMicros;

void loop()
{
    unsigned long currentMicros = micros();

    if ((currentMicros - previousMicros) >= INTERVAL_LENGTH_US)
    {
        previousMicros += INTERVAL_LENGTH_US;

        int val_a0 = analogRead(A0);
        int val_a1 = analogRead(A1);
        int val_a2 = analogRead(A2);
        int val_a3 = analogRead(A3);

        Serial.print(((double)currentMicros) / 1000000UL, 1); // 1 is the number of decimals to print
        Serial.print('\t');
        Serial.print(val_a0);
        Serial.print('\t');
        Serial.print(val_a1);

        Serial.print('\t');
        Serial.print(val_a2);
        Serial.print('\t');
        Serial.println(val_a3);
    }
}

NOTE: The millis() function is replaced by micros() according to Edgar's and Nick's comments.

Change just the define to change the sample time. Now its set to 1000us (i.e. 1ms, so 1kHz), but don't go much higher otherwise you will have to check accurately the sampling time and the transfer speed. The t variable is not needed anymore.

Just a side note: this will also fix the bug in your code that prevents the program to display the current timing (instead of printing 2.5 it prints 2.0).

If you need a faster sample rate you should use another timer to get the correct timing, but again avoid delays. Not needed anymore


Led on when not supposed to be So I made a program that controls two LED's when two buttons are pressed, but one of the LED's comes on when the button isn't pressed. And what's weird is that if I literally move around the breadboard the LED might turn off for a little, and if hold the button down while doing it the LED remains solid. I have done a lot of taking out and switching wires without any unexpected effects. However, if I switch the LED wires the other LED turns and stays on while the first one turns off, so I am pretty sure that it is a programming error. Here is my code:

const int ledPin1 = 8;
const int buttonPin1 = 1;
const int ledPin2 = 9;
const int buttonPin2 = 2;

int buttonState1 = 0;
int buttonState2 = 0;

void setup()
{
  pinMode(ledPin1, OUTPUT);
  pinMode(buttonPin1, INPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(buttonPin2, INPUT);
}

void loop()
{
buttonState1 = digitalRead(buttonPin1);
buttonState2 = digitalRead(buttonPin2);

  if (buttonState1 == LOW)
  {
    digitalWrite(ledPin1, HIGH);
  }
  else
  {
    digitalWrite(ledPin1, LOW);
  }

  if (buttonState2 == LOW)
  {
    digitalWrite(ledPin2, HIGH);
  }
  else
  {
    digitalWrite(ledPin2, LOW);
  }
}

The behavior you describe is symptomatic of a floating input.

I guess you have directly wired your buttons between input pins and +5V (or GND, that won't change the observed behavior).

The problem is when you don't push the button, the input pin is left floating and can be read as HIGH or LOW based on strange factors.

The solution to this is to use pullup (if you connect the other side of the button to GND) or pulldown (if your button is connected to +5V) resistors.

The following image, off the arduino website, shows such a circuit with a pulldown resistor, i.e. connect the switch to +5V and the resistor to GND:

An even simpler way is to connect the buttons to GND and use pinMode(pin, INPUT_PULLUP); in setup().


0.96" OLED and Arduino UNO usage error I have Arduino UNO with 0.96" OLED display with 128(width)*32(height). It is said that I have to edit Adafruit_SSD1306.h for my 128*32 OLED, okey I did it from 128*64 to 128*32 but I still get the compiler error:

ssd1306_128x32_i2c.ino:54:2: error: #error ("Height incorrect, please
fix Adafruit_SSD1306.h!");

Yes, I fixed the Adafruit_SSD1306.h file, but now, it is still gives me a compiler error:

C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h: In member
function 'uint8_t TwoWire::requestFrom(uint8_t, uint8_t, uint8_t)':
C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h:47: error:
too many arguments to function 'uint8_t twi_readFrom(uint8_t,
uint8_t*, uint8_t)'
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:85: error: at
this point in file
C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h: In member
function 'uint8_t TwoWire::endTransmission(uint8_t)':
C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h:48: error:
too many arguments to function 'uint8_t twi_writeTo(uint8_t, uint8_t*,
uint8_t, uint8_t)'
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:140: error: at
this point in file
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp: In member
function 'virtual size_t TwoWire::write(const uint8_t*, size_t)':
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:195: error:
invalid conversion from 'const uint8_t*' to 'uint8_t*'
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:195: error:
initializing argument 1 of 'uint8_t twi_transmit(uint8_t*, uint8_t)'

How can I use my four-pin OLED display with no errors?

May I suggest the following. I found this fork of the Adafruit library which works better than the one they have on their website Adafruit_ssd1306syp. The original Adafruit_ssd1306 library doesn't play nice with SPI and when you want to have your OLED running on i2c and use the SPI for something else. This is a great resource. Download, unzip to your libraries directory. Then run this sketch:

#include <Adafruit_ssd1306syp.h>

#define SDA_PIN A4
#define SCL_PIN A5

Adafruit_ssd1306syp display(SDA_PIN, SCL_PIN);

void setup() {

  display.initialize();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  printM("Starting Demo...");

}

void printM(String mess) {

  display.println(mess);
  display.update();
}

void loop() {

  printM("working");
  delay(1000);

}