Which side should I connect the resistor on? I understand that when connecting an LED and a resistor in series; the resistor can be placed on any side of the LED as the current will remain same in a series connection. Please correct me if I'm wrong, but I was under the impression that conventionally the electrons flow from positive to negative. So shouldn't the resistor be placed before an LED to limit the flow of charge.

In this scenario the negative is connected ground and the positive to a power source. So I don't understand the chain Link analogy as well. Where the whole chain moves as a whole because here the flow ends with the GND right ?

Resistor on any side of led will intercept current flow.
Just use another analogy with water, tube and water tap.


The 3.3 volts of the USB To TTL I'm using ESP with USB to serial converter (D-SUN) is it possible to use the 3.3 volts of the USB instead of the Arduino Uno?

I don't know what that adapter is (a link would be nice, or at least the chip number it uses) but in general the 3.3v on a USB TTL adapter can only provide a small current. For instance the FT232RL can only provide up to 50mA at 3.3v. That may not be enough current to drive the RF circuitry of the ESP. The early Arduinos used the FT232RL chip for the USB interface and it was the 3.3v from that which was used for the 3.3v header on the Arduino. This was somewhat of a failing with those Arduinos since the 50mA limit was a real problem when people started using more 3.3v devices. That was one of the driving forces (as well as cost) in the decision to switch to an MCU for the USB interface.

So to be on the safe side I wouldn't use the 3.3v from the USB adapter to power the ESP. You are better using a 5v to 3.3v regulator circuit driven from the 5v of the USB. And yes, that could be a whole Arduino, or build your own on some stripboard.


Simple reading and writing on Floppy Disk I am trying to interface a 3.5" floppy drive (read and write data onto floppy disc). Since I need to write just few bit long number on it (16 is more than enough) I am thinking I could write it track-wise (each track is one bit), which gives me teoretically 80 bit long number, so I could write 4 times 16 bit long number for some redundancy.

I found this code, which solves reading data out. For writing I found this page which says, that writing should be similar easy process.

I attached code I am running here. Reading seems to work, but writing not. The interesting part of code is:

void writeData(byte data){
  Serial.println("Writing");
  digitalWrite(writeEnablePin, LOW); //starting spining a motor
  digitalWrite(motorEnableBPin, LOW); //enabling motorEnable
  stepAllTheWayOut(); //moving head to the edge of drive
  for(unsigned i = 0; i<10; i++){ //repeating 10 times
    for(unsigned index = 0; index<=8; index++){ //repeating 8 times (there are 80 tracks)
      digitalWrite(writeDataPin,bitRead(data,index)); //setting data pin
      Serial.print(bitRead(data,index)); //printing out what is being written
      delay(500); //spinning for a while to write all over the track
      digitalWrite(writeEnablePin, HIGH); //stepping not working when writeEnablePin is LOW
      stepIn();
      digitalWrite(writeEnablePin, LOW);
    }
    Serial.println("");
  }
  digitalWrite(motorEnableBPin, HIGH);
  digitalWrite(writeEnablePin, HIGH);
}

The output is:

Setup done.
Writing
010101010
010101010
010101010
010101010
010101010
010101010
010101010
010101010
010101010
010101010
Reading
111001000
101010001
110111001
001000101
001011001
111111101
110101101
111110011
111111001
101111110

The output is not what should be written. (the bits are changed every time i run the code)

Any idea what am I doing wrong when writing?

for(unsigned index = 0; index<=8; index++)

I think that need to be

for(unsigned index = 0; index<8; index++)

Otherwise you are trying to read the 9th bit in a byte.


Translating WS2812-LED-Strip-IDs when cutting up a strip to multiple parallel ones Lets say i have 1 meter of WS2812 Strip at 60 LEDs per meter. Now i cut the strip up in to 6 single strips but keep the wiring the same and lay them out in parallel. So it would look something like this

1   |  11  |  21 ...

2   |  12  |  22 ...

3   |  13  |  23 ...

...

10   | 20   | 30 ...

Is there any library that would allow me to easily translate this? If i for example want to work with rows, turn a certain row in a certain color, treat certain sub-strips as if they were an individual one, etc etc...
I'm sure i can't be the first one who had this problem?

No, there is no library.

It's just simple maths.

If all your strips are the same, then you just multiply the strip number by the number of LEDs per strip, and add the number of the LED you want in that strip.

So, assuming 10 LEDs per strip:

lednumber = 10 * strip + led;

You can make a little macro to do it for you if you like:

#define STRIP2LED(S, L) (((S) * 10) + (L))

Then you can use such things as:

// Set all LEDs on strip 3 to red
for (uint8_t i = 0; i< 10; i++) {
    leds[STRIP2LED(3, i)] = CRGB::Red;
}


Driving numerous chips from 2 separate SPI connectors w/ Arduino Micro I want to drive numerous chips (L9823, TLC5925, ADG1414, MCP23S08) from an Arduino Micro as well as read input from analog pins connected to momentary buttons, toggles, potentiometers and such. The chips and input controls will be on various boards connected to the Arduino using ribbon cables.

The current idea is to have two sets of 8 pin FFC connectors with the following pins:

FFC digital "bus" conductors:
--
SCLK
VL
SDI
RST
SDO
LE3
LE2
LE1

The clock, VL (5V), SDI and SDO will be shared by both connectors but I still need 6 latches (which can also be commandeered for an interrupt or analog input) and 2 reset pins. This will allow me to run up to 3 types of chips per connector (minus latches used for something else).

I will also have a third 8-conductor FFC connector for 7 analog inputs (the eighth conductor is 5V analog ref).

So my question is, does anyone see any holes in this strategy? I don't think I'm going to try to even breadboard something like this. PCB fab is so easy now (and the first run is always wrong anyway) so I'm just going to make the boards and go from there.

So I just need to settle on what pins to use. Here is a diagram of the Arduino Micro:

So the connectors could use pins:

Connector 1 - Digital I/O:
--
SCLK SCK
VL   5V
SDI  MOSI
RST  11
SDO  MISO
LE3  A8
LE2  A7
LE1  SS

Connector 2 - Digital I/O:
--
SCLK SCK
VL   5V
SDI  MOSI
RST  13
SDO  MISO
LE3  A9
LE2  7 (Arduino INT)
LE1  5

Connector 3 - Analog Inputs:

5V
A0
A1
A2
A3
A4
A5
A6

A10 and A11 are reserved for other purposes as well.

Does this look ok?

UPDATE 1:

I have updated the text of this question to consider many of the great comments. The changes include:

Share MISO and MOSI
between connectors. Not sure why I thought I needed to use separate
ports for the different connectors. SLCK, MISO and MOSI should
indeed be shared by both connectors.
Moved 5V to be in between
SCK and MISO and moved RST to be in between MISO and MOSI. The idea
is that the low impedance of these lines will shield from capacitive
crosstalk described by Majenko. The connectors are 1mm pitch which
isn't terribly small so hopefully this will not be an issue. It does
make routing a little harder since the data pins tend to be next to
each other but the same bus is going to connect to multiple boards
in a daisy chain fashion so capacitive crosstalk could definitely be
an issue. Fortuntely things don't have to run really fast since
everything is ultimately for interfacing with humans who are
relatively slow.

The micro only has one SPI bus. It is SCK/MISO/MOSI. You may want a second one, but you don't have one.  You can't magic one up out of thin air.

You could emulate one in pure software (bit-banging) but it won't be anywhere near as efficient as using a real hardware one.

Why do you feel you need to have two independent buses anyway? What are you wanting to achieve that you can't achieve with a single shared bus? That same bus can quite happily appear on multiple connectors.

One thing to note with your strategy: Ribbon connectors and SPI don't mix well together.  There is a lot of crosstalk and capacitance in a ribbon cable that high speed serial communication really doesn't like.  If I had to use ribbon cable for SPI communication for anything longer than a couple of inches I would use twice as many connections and interleave ground between each signal.  That is what the ribbon cables for later IDE drives in PCs used to get higher speed, more reliable, communication down ribbon cables.


Pin identification for a salvaged LCD I salvaged an SPI interface LCD from an old CDMA telephone. It seems it uses SPI to display something on the screen. The pins marks are DATA, CS, SCLK, BL, VDD, GND, LED, A0, and RES. How do I wire it up to an Arduino?

They seem pretty self-explanatory. Data, sclk and cs are normal SPI MOSI, CLK and CS. A0 is probably equivalent to C/D. RES is reset - tie high to run. Power and ground are obvious. The others look related to the back light.

However... How are you going to operate it? Do you know the SPI instructions to send? They will be specific to the display, so without a datasheet you're pretty much stuffed.


Updated Arduino IDE and Arduino not working I've had the 1.0.5 IDE on my PC, which worked great. Now I've just decided to update to 1.6.6. After some stupid Java errors and trial and error, I got it to work.

I recompiled my project. Massive errors. Fixed the errors and compiled again.

It stated "Uploading..." That took much longer than before, but I saw the "This takes xxx memory and xxx bytes on the device" yadi yadi ya.

I decided to unplug the Arduino, swap some jumpers and reconnect it (as I've always done). Only this time - I hear 3 beeps from my PC (the sound you hear with broken USB devices). The COM port is no longer recognized.

How do  I fix this? Did that IDE upgrade just brick my Arduino?

Allright, seems to be fixed. After a 3rd reinstall it seems like its fixed. I reinstalled the whole package, including the drivers, and now it seems to recognize the device again.

Also the compiling now stops properly when done and shows "upload complete".


Output voltage of PIR sensor Case 1
I am measuring output voltage of PIR sensor, I am getting 3.3v

Case 2
I have connected a resistor and a led to output of PIR sensor. Now when I measure voltage at the output pin of the sensor, I am getting 2.04v only.

In case 2 as the output voltage is dropped, it is not able to trigger a high state to arduino pin.

Where am I going wrong? What shall I change?

The PIR can’t provide enough current to drive the led. The maximum current for the BIS0001 is 10mA.

Either increase the resistor value, and accept that the led is less bright.

Or use a transistor to drive the led.

Or connect the led to an Arduino pin and turn the led on by code, based on the input pin connected to the PIR


Arduino Nano, ESP8266-01 communication In my last question I got the suggestion to get a voltage regulator to power my ESP8266, so I went out to buy one and in the end my ESP8266 turned on. Then I started wiring the Tx/Rx pins through the Logic Level Shifter and tried out this piece of code I found online

// Basic serial communication with ESP8266
// Uses serial monitor for communication with ESP8266
//
//  Pins
//  Arduino pin 2 (RX) to ESP8266 TX
//  Arduino pin 3 to voltage divider then to ESP8266 RX
//  Connect GND from the Arduiono to GND on the ESP8266
//  Pull ESP8266 CH_PD HIGH
//
// When a command is entered in to the serial monitor on the computer
// the Arduino will relay it to the ESP8266
//

#include <SoftwareSerial.h>
SoftwareSerial ESPserial(2, 3); // RX | TX

void setup()
{
    Serial.begin(115200);     // communication with the host computer
    //while (!Serial)   { ; }

    // Start the software serial for communication with the ESP8266
    ESPserial.begin(115200);

    Serial.println("");
    Serial.println("Remember to to set Both NL & CR in the serial monitor.");
    Serial.println("Ready");
    Serial.println("");
}

void loop()
{
    // listen for communication from the ESP8266 and then write it to the serial monitor
    if ( ESPserial.available() )   {  Serial.write( ESPserial.read() );  }

    // listen for user input and send it to the ESP8266
    if ( Serial.available() )       {  ESPserial.write( Serial.read() );  }
}

But I when I tried sending "AT" to the ESP via the Serial Monitor nothing happend.

This is my current wiring, I hope it's not to unclear:

Hopefully someone can help me :)

Step 1: Turn On Your ESP8266 Module by Using Arduino Nano 3.3V Dc Output Pin. Remeber sometimes Arduino board is not delivering sufficient voltage to the ESP8266 module. You can use a 3.3 V ( Do not exceed input voltage from 3.3v) regulator ( AMS1117 ) to power this module. A voltage divider circuit is used to drop the Arduino 5V to ESP8266 3.3 V.

Step 2: Here is the schematic Diagram, in my code I used Digital pin 2 as a Tx and D3 as an RX.

Step 3: Open Arduino IDE and Paste the source code in the window just like shown in the picture.

Step 4: You are ready to send At Commands to Your ESP8266 Module. Remember you will see a Garbage value during Serial Communication.

AT – Will give OK on the serial monitor, if Not just unplug vcc Pin of ESP8266 Module for a moment and reconnect again.

Send AT+RST – Command to Restart module / Optional Command

Send AT+GMR – To get the firmware version

Send AT+CWMODE? – Set Module to a Dual Mode Sucha as Standalone + Access Point mode.

Send AT+CWLAP – Command to Search Nearby Wifi Access Point. Find your Wifi Name in the Search Result.

Send AT+CWJAP="Your Wifi Name","Your Wifi Password" – Command to Connect to WIFI.

Send AT+CIFSR – Command to Check Allocated Ip given by your Wifi to your ESP8266 Module/Optional Command.


How to Segment Accelerometer Signal at idle points I'm using an 3 axis Accelerometer(GY-521) to get the acceleration data and also the gyroscope to get the gyro data. I want to segment the signals at the idle points so that i can get the segmented signal at the idle points.

Is there any algorithm or example code that i could use to segment this kind of signal?

Any help would be appreciated.

Thank You.

There are many algorithms you can use. I would advise you to look carefully at the data and the "idle state" and see what is always different. Try everything you can think of and see what works best, or if one does everything you need just stop there.

It might be that you can just calculate if the accelerometer values go over a certain threshold, but that requires that either the orientation be know or the threshold being over 1g.

You could also calculate the rate at which the accerometer value is changing by subtracting the last value (the derivative if you are up on your calculus) and threshold that value, which might produce better results.

You could also calculate a running average and then compare the current value with that. If the numbers match (or are very close) then you can say the accelerometer has been idle. This has the effect of making a changing threshold relative to the most recent activity tuned by the average's response.

I doubt any of these will be perfect, so you might require the algorithm to say "idle" multiple times in a row before changing state from "active" to "idle", or something to that effect.


How to connect a Pressure Sensor-MPX10DP to an Arduino? I'm very new to Arduino, I'm trying to connect an air pressure Sensor without success.

I followed this tutorial:

Arduino Air Pressure Measurement

The values I'm getting are very weird and the variations when I blow in the sensor are not more than about +/- 0.2.

So, the tutorial does use the same model, is that why? I need something else?

Any help will be very appreciated.

The MPX10DP does not have an amplifier inside. The output is the output of the internal wheatstone bridge. It is not even compensated for temperature.

This is the manufacturers page about the MPX10 series: nxp.com MPX10 series.

You need an instrumentation amplifier and perhaps a temperature compensation. The INA125 is an instrumentation amplifier. It was used in the past with the Arduino a lot. Nowadays, most sensors are digital, and the bare sensors with wheatstone bridge output are not used that often anymore.

When you connect both sensor outputs to two Arduino inputs (without amplifier), then the difference is 35mV for 10kPa. The resolution is in theory 5V / 1024. The overall accuracy for two analog inputs perhaps 9 bits, then you can measure the 10kPa in 3.5 steps (about 2 or 3 kPa resolution).
If you seriously want to use this specific sensor, and don't want to use extra hardware, then you might have a look at my question about the differential mode and gain that is possible with the Arduino Mega 2560 and Leonardo.

Or you could buy a pressure sensor with 0...5V output, that can be connected to the Arduino analog input. The tutorial you mentioned uses the MPX5010. That sensor has a amplifier inside and is temperature compensated. They are reliable and ratiometric with the 5V, therefor super easy to use. With a lot of averaging in the code, you can get a high (relative) accuracy.


How to reset the count/data after HTTP.POST? I have a project that records interrupts from a reed switch to nodemcu.
It records like this: 0.3,0.6,0.9,1.2 Then what I want to happen is to go back to zero when it successfully HTTP.POST to a webserver.
How can I do it? Thanks!
volatile float rainrate = 0.3;
volatile float total;

void count {
  total += rainrate;
}

Try putting your total variable to 0, like this:
total = 0;
It should work like this.


Is it possible to run a monochrome LCD without driver circuit with an Arduino Uno? I have an old monochrome LCD panel that I removed from a calculator. The LCD panel has no standard input pins, because it's directly connected to a driver on which the calculator software runs.

Is it possible to run the LCD without the calculator software? All pins of the LCD would be available (marked in blue). The pins marked in red were connected to the keyboard of the calculator.

Normally such LCDs are custom designed, mass produced displays especially for this calculator product. Thus it is very unlikely to find a datasheet or even a meaningful part number for it.

Most likely the pins on the LCD are directly connected to the corresponding fields on the LCD. In an LCD you have liquid crystals between two electrodes, which change their orientation, when a voltage is applied to the electrodes, which changes the light absorption of the layer. You need to apply the correct voltage to a pair of pins to activate their field. Most likely all of the fields or a few groups of them have a common electrode (which would be 1 pin). Without any documentation you are bound to experiment with the display, until you have found the correct voltages and pin arrangements. You might break the display in the process (for example through excess voltage).

I haven't done this myself, but googling gives an interesting result:

This project, where they hacked the LCD of a cheap calculator for a waveform generator (though the display seems to be way less complex than yours) They seem to use 1.5V as voltage, so this might be a good starting point.

Your display has many pins. Depending on the Arduino model, that you use, you will fast run out of pins to use. You can try arranging the pins into a matrix, which would mean multiplexing the fields (turning them on and off fast one after another). Or you can buy additional parts to extent your pin count, for example shift registers.

As jsotola wrote in the comments (and as several forum threads on web web state), you should not put a constant voltage onto the display, since this will damage it. (I guess the liquid crystals will degrade fast because of their polarity, which make the work in the first place). Instead you have to place an alternating voltage at the pins, which changes it's polarity. The  net voltage (The integrated voltage over time) must be zero. Thus you need to alternate the applied voltage. If you provide a span of 1.5V, you need to change between +0.75V and -0.75V.

As the display shouldn't need too much current and the voltage requirement is relative to the LCD ground, you might get way by setting the LCDs ground with a voltage divider to 2.5V and then operating around that. Though I'm not sure about that.

Otherwise you might need to actually change the polarity. This would also just need 1 extra digital output pin as the ground pin. One polarity would be the LCDs ground pin to Arduino's ground (outputting LOW at the digital pin) and the other pins to the needed positive voltage (HIGH divided down over a voltage divider or similar). The other polarity would be LCDs ground pin to the needed positive voltage (HIGH divided down over voltage divider) and the other pins to ground (outputting LOW).

As described above, hooking this bare LCD to the Arduino is not done fast and easy. You can try it, if you like to do it. But if you want to get your project (whatever it is) done fast, you should instead buy a LCD with integrated controller, which are mostly ready to use, and for which there are already libraries.


ESP-12e, Arduino IDE, NeoPixel Strip - Flickering I have a NeoPixel RGB strip connected directly to my NodeMCU ESP12-e board. I'm using Arduino IDE with the NODEMCU 1.0 ESP 12-e module to programm the board.

ESP12-e | NeoPixels
GND    ---> GND
3.3V   ---> +5V
GPIO0  ---> Din

With the 3.3V output I have a strange flickerin on the LEDs.
When I use the VIV 5V output of the ESP12-e the flickerin is gone, but the lights turn off after a few seconds and some lights turn on with strange behavior.

I guess 5V is to much for the board? What can I do to get rid of the 3.3V flicker?

EDIT: I'm using WS2812B LED Strip Band with 224 LEDs 5050 SMD connected directly (see above) to a NodeMCU ESP-12e (http://learn.acrobotic.com/uploads/esp8266_devkit_pinout.png)

I'm using:

#include <ESP8266WiFi.h>
#include <Adafruit_NeoPixel.h>

I'm turning LEDs on for example like this:

#define PIN 0
#define NUMPIXELS 224

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

int individualPixels[NUMPIXELS];
  void allOn(){
      for(uint16_t i=0; i<pixels.numPixels(); i++) {
        individualPixels[i]=1;
        pixels.show();
      }
    }

   for (int i=0; i<sizeof(individualPixels); i++){
    if (individualPixels[i]==1){
      pixels.setPixelColor(i, pixels.Color(red,green,blue)); //Set Neopixel color
    }
    else{
      pixels.setPixelColor(i,pixels.Color(0,0,0));
    }
  }
  pixels.show();

The ESP12-e is plugged in via USB Power

Thanks in advance

Have a google for (WS2812 or Neopixels) and ESP, it should give several good hints on how to wire it up reliably. Also really read this: https://learn.adafruit.com/adafruit-neopixel-uberguide/overview .

But some things to consider:

WS2812 requires 5V, so you do want to use a 5v source, not 3.3v.
Make sure all your grounds are connected together, especially if you have a separate power supply for the leds.
The data input on the WS2812 needs a 5v high signal, especially when the WS2812 is (correctly) powered by 5v. This means you probably need some kind of level shifter, which needs to be able to switch fast as well, cause it's a pretty high frequency signal.
224 WS2812's can chew up a lot of power, so make sure your 5v source can handle that. When all are set to full white, it's 20ma per color per led, that's 60ma per led, so 13,44 AMP maximum. Your average USB charger isn't gonna cope with that :) You can use a power supply which provides less power if you make sure you only turn on a few leds/colors at a time, but if you accidentially turn on more, voltage is gonna drop and stuff will stop working :)


what library should I #include when using switch-case statement I receive an error code of: 'switch' was not declared in this scope
The code is correct so I assume that the necessary library was not included.
Please tell me the correct #include to use.
swith(pwm){
  case 0:   Serial.print(pwm); Serial.print("   ");_delay_ms(2000);
            break;
  case 31:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 63:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 95:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 127:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 159:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 191:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 124:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 156:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 188:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 220:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  case 252:  Serial.print(pwm); Serial.print("   ");_delay_ms(100);
            break;
  default:  break;
}

It seems you have a syntax error: write switch instead of swith.


How to make auto keyboard using arduino nano V3.0 ATmega 328P ? I have an Arduino Nano v3.0 ATmega328p board. I want to make an auto keyboard that types in a string when its plugged in. I have googled and found that these chips doesn't support that feature unlike "pro micro". keyboard.h is not supported with this chips. So is there any alternative way to use it as a HID and emulate keyboard inputs using any other additional shield other than using the built in USB port. Im a noob in this field, please help. Thanks in advance.

I found this link : http://www.practicalarduino.com/projects/virtual-usb-keyboard  Is that what you've been looking for?


I got a missignatured ATmega328-PU. How can I fix that? Sometime in the past, I was burning bootloaders on a fresh batch of four ATmega328-PU using the Arduino IDE (notice there's no P after 328 - it's the slightly cheaper non-picopower version of the MCU, not to be confused with the ATmega328P-PU with a P), and was surprised with the following message from avrdude:

avrdude: Device signature = 0x1e950F
avrdude: Expected signature for ATMEGA328 is 1E 95 14
Double check chip, or use -F to override this check.

That means avrdude thought the chip was not what its label said. Then I changed the chip type on my Arduino IDE to ATmega328P-PU and avrdude burned the bootloader without complaints. What that means is that the chip was labelled as one MCU and internally it responded as another, slightly different.

What I would like to know is:

How rare is this event? Has anyone had a similar experience? (Original question, off-topic)
Is it possible to fix this? How can I fix the signature so that avrdude recognize the chip correctly?

This is a cross-post from EE.SE. I posted this question there but didn't attract much attention, so I wanted to see if anyone from our community had a similar experience.

While browsing sparkfun, i have found several news posts that show their struggle with mislabeled chips. Here are a few:

https://www.sparkfun.com/news/350
https://www.sparkfun.com/news/384
https://www.sparkfun.com/news/364

Sparkfun had received a questionable shipment if ICs from a new seller in china. They decided to test them before sending them into production, and none of their test boards worked. Using nitric acid, they were able to remove the case of the ICs and fould a hunk of metal that looked like copper.

In another article, they dissected some suspicious ICs from Atmel, and found an ON semiconductor silicon wafer inside. The chips were not functional ATmegas, but they did have silicon, unlike the other ones.


Testing ID and Serial Communication (Update) Here is my challenge: I have to create a sketch where I would have a prompt asking the user to enter an ID. If it is successful, it would turn on the green LED and response with "Hello, your name is so-so."  If it failed, it would turn on the red LED and response with "Invalid username! Try again."

The code is here:

//Establish myID as CHAR data type
 char myID = 'tg123';
 //Establish testID to receive data to be tested against myID
 char testID;

 //Establish green and red LEDs to PWM pins
 const int gLED = 10;
 const int rLED = 5;

 void setup()
 {
  //Establishing baud rate at 9600
  Serial.begin(9600);
  pinMode(gLED, OUTPUT);
  pinMode(rLED, OUTPUT);
 }

 void loop()
 {
  //Act when there are data in the buffer
  while (Serial.available())
  {
    testID = Serial.read();
    //If data = myID, turn on green LED and acknowledge
    if (testID == myID)
    {
      digitalWrite(gLED, HIGH);
      digitalWrite(rLED, LOW);
      Serial.println("Hello! Your name is Trevor.");
      delay(5000);
    }
    else
    {
      digitalWrite(rLED, HIGH);
      digitalWrite(gLED, LOW);
      Serial.println("Invalid ID! Try again.");
      delay(2000);
    }
  }
 }

Two problems I have had with this:

The damn thing would print the line "Please enter your ID:" infinitely if it was inside the loop, so I got fed up and moved it to the set up, and
no matter what I enter in the serial monitor, it does not do anything.

Update: After reading Arduino's website, I found I can predefine the char data type by adding char myID = 'tg123';.  It is getting closer to achieving what I want, but it's exhibiting some strange behavior.  When I type in exactly tg123 in the serial monitor, it would report the error message as defined in the sketch before passing.

You are assigning a string to a single character here.

  char myID = 'tg123';

Instead you should make it a String variable. And compare it after all the characters are recieved.

  String myID = "tg123";

And Here is the modified code you should test with. In this case I have assumed you simply write the ID (string) in serial terminal and hit enter.

N.B. If you want to enter each character one by one, then it will not be able to catch the whole string. For this case you have to add some time-out to wait for next character to arrive.

String recvData = "";
void loop()
{
  while (!Serial.available());
  while (Serial.available())
  {
    char ch = Serial.read();
    recvData += ch;
  }
  if (myID == recvData)
  {
    digitalWrite(gLED, HIGH);
    digitalWrite(rLED, LOW);
    Serial.println("Hello! Your name is Trevor.");
    delay(5000);
  }
  else
  {
    digitalWrite(rLED, HIGH);
    digitalWrite(gLED, LOW);
    Serial.println("Invalid ID! Try again.");
    delay(2000);
  }
  recvData = "";
 }


Help me for interfacing Arduino with AMTP32M VOICE IC i'm trying to get control an Aplus chip aMTP32M (stores audio samples) with Arduino . this amtp32m ic provide CPU SERIAL MODE its come with DATA and CLOCK pin.i try Spi mode with Amtp32m ic but its not working.
Please help me for this.
Link for  for DATASHEET of AMTP32M IC -http://www.aplusinc.com.tw/proimages/Mtp%20Vioce%20Ic/aMTP32M/aMTP32M/Datasheet/aMTPxxM-Datasheet_V1.1_20141216.pdf

Finely i try the below code for serial mode. it's worked perfectly...
type def union
  {
unsigned char BYTE;
struct
{
    unsigned        BIT0:1;
    unsigned        BIT1:1;
    unsigned        BIT2:1;
    unsigned        BIT3:1;
    unsigned        BIT4:1;
    unsigned        BIT5:1;
    unsigned        BIT6:1;
    unsigned        BIT7:1;
};
}ByteToBit;

void Play(unsigned char Val)
{
  ByteToBit SectionNo;

  SectionNo.BYTE = Val;

CLOCK = 1;
DATA  = 0;
CLOCK = 0;

DATA  = SectionNo.BIT0;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT1;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT2;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT3;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT4;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT5;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT6;
CLOCK = 1;
CLOCK = 0;
DATA  = SectionNo.BIT7;
CLOCK = 1;
CLOCK = 0;

DATA  = 0;
CLOCK = 1;
DATA  = 1;

return ;
}

 void main(void)
 {
    unsigned char SectionNo;

CLOCK = 1;
DATA  = 1;

SectionNo = 0x00;
while(1)
{
    Play(SectionNo);
    Delay_1mS();        // Wait for BUSY set up time...
    while(BUSY);        // Voice playing...
    SectionNo++;
}

return ;
}


pull-up or pull-down Do you have to build the circuit on an external board every time you decide there is a need
for a pull-up or pull-down circuit? If not, then what is the alternative and how can you use
it?

This depends on what you are doing.
The IO hardware of the Uno (more specific the Atmega328p, which is the used chip) has internal pullup resistors, that can be used, when the pin is configured as input. This can be done in one line:
pinMode(pin_number, INPUT_PULLUP);

This is true for all AVR based chips.
Other, more complex and capable chips also have an internal pulldown resistor (as I remember this is true for the ESP32 for example). In this case you can do
pinMode(pin_number, INPUT_PULLDOWN);

If you are using special hardware of the Arduino, it depends on the hardware itself, since in most cases the normal IO hardware is internally not connected to the pin, when using this hardware. For example: The internal pullup resistor will not be active, when doing an analog measurement with the ADC (like via analogRead()).


How do I properly receive MIDI with Arduino, with 6n138? UPDATE : I still can't receive MIDI as of 2019/07/01.

Here goes so far : I'm trying to follow this schematics from instructables, using 6N138. To make it easier, I'm going to copy his schematics.

===================================

I'm using Arduino Mega. I tried to find specific topic about this and can't find any.

The target is actually send and receive MIDI, then replace the whole Arduino Mega to ESP8266 (probably the ESP-01, or Wemos D1), but I'm afraid it is too specific.

Here's the code so far on PasteBin

Here's my work so far.

The diodes were replaced with LED, because I don't have one Original guide here.
But that schematics on that thread also didn't work for some reason.

Most start at the midi site at playground.arduino.cc.  But there are numerous web sites across the Internet.  It is important to understand that the MIDI interface uses a current loop to send and receive data.  While the Arduino normally uses voltage levels to communicate.  As such, an electronic interface needs to be built or bought to convert between these two types of signals.  Some interface designs are simple and limited.  Others are complex and robust.


Simple serial message not consistent (sometimes jumbled up) I have the following code, it works (most of the time) - yet it's not 100% reliable and now and then will send through a double message on one line or 2 subsequent alpha characters:
const byte interruptPin0 = CONTROLLINO_IN0;
const byte interruptPin1 = CONTROLLINO_IN1;
int counter1 = 0;
int counter2 = 0;
unsigned long previousMillis = 0;
unsigned long interval = 2000;
int a = 60;
char buffer1[256];
char buffer2[256];

void setup()
{
  pinMode(interruptPin0, INPUT_PULLUP);
  pinMode(interruptPin1, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin0), pin1Fired, RISING);
  attachInterrupt(digitalPinToInterrupt(interruptPin1), pin2Fired, RISING);
  Serial.begin(9600);
}

void loop()
{
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    sprintf(buffer1,"A%d",counter1);
    Serial.println(buffer1);
    sprintf(buffer2,"D%d",counter2);
    Serial.println(buffer2);
    counter1 = 0;
    counter2 = 0;
  }
}

void pin1Fired()
{
  counter1 = counter1 + 1;
}

void pin2Fired()
{
  counter2 = counter2 + 1;
}

Result:

This later causes a problem when my code on the other end of the serial comms expects [LETTER][NUMBER].
What have I missed here? I'm relatively new to C for Arduino so quite possibly took a bad approach here?
I've tried to avoid sending serial comms from the interrupt, I read that was risky - hence me tracking the interrupt counts separately.
Can also confirm baud rate matches.
EDIT
To confirm MCU resets I have printed in setup - note: no interrupts firing, still the same issue:

My guess is that an interrupt is occurring during your reading or writing of the counter variables.
Since the variables are bigger than the native size of the registers in the CPU multiple instructions are required to work with them, and an interrupt can occur right in the middle of that work which changes the values it's working on. That can cause a mess (though I wouldn't expect it to make that kind of mess, TBH).
You should wrap all accesses to the counters that aren't in the interrupts inside a critical section. This is a segment of the code where interrupts are not allowed to happen. For obvious reasons you want to keep that code as short as possible.
Also in the code you have given there is no need for your buffers and sprintfs. You can just use multiple Serial.prints to achieve the same result with a much smaller code/memory footprint.
Here's an example:
void loop() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;

    // Copy and reset the counter values in a critical section
    noInterrupts();
    int nowCounter1 = counter1;
    counter1 = 0;
    int nowCounter2 = counter2;
    counter2 = 0;
    interrupts();

    Serial.print("A");
    Serial.println(nowCounter1);
    Serial.print("D");
    Serial.println(nowCounter2);
  }
}

Also your counter variables should be volatile since they are accessed from both the interrupts and the main loop:
volatile int counter1 = 0;
volatile int counter2 = 0;


How Do I Send An Email WITHOUT An Ethernet or WiFi Shield I can only find info relating to the wifi shield, but I want to send an email without the wifi shield. For now, I just plan on leaving my arduino plugged into a computer, so I just want to use the computer's network connection. Is there a library or something I can grab for this?

If you mean plugged-in via USB, then no. There's nothing you can do on the Arduino that would let you use the computer's network connection directly.

You would need to have a program running on the computer which would communicate with the Arduino via serial. It would effectively act as an intermediary, sending the email on behalf of the Arduino.

Unfortunately, I suspect you'd have to write the program yourself. It's possible that something similar already exists, but at the very least you'd probably have to modify it to suit your needs.


How to send int[][] as a byte array through Serial I have int arr[50][2]; and I need to send it through Serial. But I don't know how to do it. is it possible?

In the comment you write that the receiving end is an Arduino too. Then you can send the data in binary form.

To send the array:

Serial.write((byte*) arr, sizeof(arr));

(byte*) is cast of the memory location of arr to a byte array
sizeof returns the size of the array in bytes

To receive the binary data you must know the size. Here we read 100 16-bit integers:

Serial.readBytes((byte*) arr, 100 * sizeof(short));

Function readBytes is one of the 'timed' functions of Stream. It waits for the next byte (until timeout).

If one Arduino is 8-bit and the second is 32-bit, then use the type short instead of int, because the size of type int is different, but the type short is 16 bit long on all Arduinos.


How do I make/get a odometer for a lunch box sized robot? Say I have given the robot a map of the place, it needs to navigate it. I need a odometer to keep track of its current position in the map. I need it to be precise up to a cm.

Can I simply use the motor's RPM and the diameter of the wheel to calculate how much distance the robot has travelled, or is there any catch?

I searched Google and could not find any odometer small enough for my robot. Most of them are for bicycles.

I had the idea to use a computer mouse (optical) to do this - cheap, easily available. You would need two, if you want to be able to measure turning rate, one on the left and one on the right.

You don't even need the whole mouse - if you pull it apart you can ditch the case, the buttons, and about half the circuitry. You will need to do some hacking to figure out how it works, but I doubt you'll find a cheaper odometer that is anywhere near as accurate.

Note: I pulled one apart, then got distracted on another project, but I can't think of a reason why it wouldn't work.


Can I use relays with 10A125V~ for my 220V~ applications, safely? I am using the TinkerKit Relay Module and recently they changed the relay mounted on the board from a white one with 10A250V~ to a black one with 10A125V~.

In my country the voltage is 220V~. Can I use the black relay in my application, safely? May be there problems that I have to be careful?

The part is obsolete now according to Mouser.  The simple answer is no, you cannot use a 120 volt part at 220 volts.  The higher voltage can breakdown the lower voltage rated parts.  It really has nothing to do with the "power" rating as there will be very little power actually dissipated in the relay.  The current handling of the contacts is one issue and that seemingly didn't change but the voltage rating change is basically saying that this part cannot work at 220volts.


Arduino: Reading DS18B20 interferes with servo I have an Arduino with a servo, INA219 (current and voltage sensor) and 2 DS18B20 connected to it.

DS18B20 are connected in full-power mode with 5k resistor connected between DATA line and +5V.

I use DallasTemperature library: https://github.com/milesburton/Arduino-Temperature-Control-Library

I get the temperature readings, but the problem is that my servo is jittering slightly almost every time temperature reading is done.
If I disconnect DATA line from pin 2 (where it's normally connected) then servo is not moving anymore and everything is fine.

Any ideas what might be causing it? I would expect servo interfering with OneWire readings, not the other way around :)

Here is the full code:
https://pastebin.com/xcES4PVT

Here is the minimal example with which I can reproduce the problem:

    #include <DallasTemperature.h>
#include <Servo.h>

#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

Servo myservo;

long previousMillis = 0;

long tempRequestedMillis = 0;

bool tempRequested = false;

void setup(void)
{
  // start serial port
  Serial.begin(115200);
  Serial.println("Dallas Temperature IC Control Library Demo");

  myservo.attach(9);

  // Start up the library
  sensors.begin();
  sensors.setWaitForConversion(false);
}

void loop(void)
{

  unsigned long currentMillis = millis();
  if (!tempRequested && currentMillis - previousMillis > 2000) {
    previousMillis = currentMillis;

    sensors.requestTemperatures(); // Send the command to get temperatures

    tempRequestedMillis = currentMillis;
    tempRequested = true;
  } else if (tempRequested && currentMillis - tempRequestedMillis > 2000) {
    Serial.println(sensors.getTempCByIndex(0));
    tempRequested = false;
  }
}

Arduino's Servo library on AVR uses interrupts; if interrupts are disabled for any amount of time, the servos will twitch.

1-Wire protocol (used by DS18B20) needs to disable interrupts for the protocol to work. Therefore, servos glitch.

There is a great explanation of the problem here: https://learn.adafruit.com/neopixels-and-servos/overview , just mentally replace "Neopixel library" with "OneWire library". Their TiCo_Servo library sounds just like what you want.


I2Cdev #include weirdness I am using Jeff Rowberg's MPU6050 library, and I simply don't understand what is going on in the following lines of the first example (MPU6050_raw.ino):

#include "I2Cdev.h"
#include "MPU6050.h"

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE
// implementation is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include <Wire.h>
#endif

So, what I got from that is, if I2Cdev is using Wire instead of some alternative I2C library, I should include Wire.h. I really don't see why that's necessary, so I removed the line in which Wire.h is included, and got this error:

C:\Users\Franco2500k\Documents\Arduino\libraries\I2Cdev/I2Cdev.h:80:26: fatal error: Wire.h: No such file or directory
     #include <Wire.h>

So, apparently, I2Cdev.h already tries to include Wire.h, but somehow fails? And another #include a few lines later goes back in time and fixes everything? Can someone explain what is going on?

The Arduino IDE means well, really it does. It copies your source, the device core, and any libraries used by your source all to a separate directory so that it doesn't poison any of their original locations unintentionally.

But of course, there's something missing from that list. The IDE doesn't copy libraries used by other libraries. Therefore if you don't include Wire.h in your .ino file then Wire will be missing from the build and you get the error observed. Cracktastic.


Do arduino librarys require the arduino to be connected to a computer? The title pretty much explains my question. If I'm using a library for example one for an accelerometer does the arduino need to be connected to my computer because it's using a library? Or is the library uploaded to the arduino and there for can run with out a computer connected?

No.  Arduino libraries (strictly speaking only the utilized parts) are permanently built-in parts of your compiled sketch.  Effectively they are "statically linked" unlike the situation with modern RAM-based computer operating systems where compiled dynamic link library code may be separately loaded into memory for a program to call at runtime.

(This isn't even really a design choice, as the basic AVR Arduino's cannot load new program code into executable memory at runtime anyway - except by reflashing themselves like the bootloader does, which would be a bit slow compared to normal dynamic linking)

Of course if you have a library which is intended to perform communication with a computer, then that connection would probably be required for it to fully operate.


Analog inputs are not working I have an Arduino ATmega8A. I tried to use its analog inputs. Initially I used a normal program without using aref and connected potentiometer at A0 and I got expected values.

After that for accuracy I used a LM431 circuit for 2.5V reference. Programmed the Arduino and I again got expected values. It was working properly until this stage.

For more accuracy I tried using LM317 1.25 reference as voltage reference for aref pin. The problem comes here. When I run the program initially the values were changing from maximum value. Like it was showing 1.25, when I changed the resistance on the potentiometer it was changing its value for a sec. and again showing maximum value 1.25. I off the circuit and tried it once again. At that time there were no changes and it was giving me maximum value.

I thought there is a problem in my LM317 circuit or my LM317.

I connected the LM431 circuit again and changed the program and run it once again, the outputs were giving me maximum value i.e. 2.5 ,outputs values  were not changing as I change resistance on potentiometer. So I tried with normal program without using aref pin, the same thing happened there.

This is program without using potentiometer

int r;
float v;

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

void loop()
{
  r = analogRead(A0);
  v = (5.0 / 1023.) * r;
  Serial.println(v);
  delay(250);
}

The potentiometer is connected at A0 and the other 2 pins are connected to + 5v and gnd. Initially it was working properly

The program using vref

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
float exRef = 2.52;

int r;
float v;

void setup()
{
  analogReference(EXTERNAL);
  analogWrite(6, 20);
  lcd.begin(16, 2);
  pinMode(A0, INPUT);
}

void loop()
{
  r = analogRead(A0);

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Voltage:");
  lcd.setCursor(8, 0);
  lcd.print(convert(exRef, r), 5);
  delay(1000);
}

float convert(float exref, int r)
{
  return (((float) r / 1023.) * exref);
}

I have interfaced Arduino with lcd too.
I set aref to 2.5 the program and connected to lm431 circuit it was working properly.
After that I connected Arduino to lm317 circuit and set aref to 1.25. As I  connected it it was giving me maximum value
After that I tried with normal program that is first one without using aref it was still giving me maximum value.

![lm317 circuit](https://i.stack.imgur.com/KvkNS.jpg

The minimum reference voltage (VREF) for the ATmega8A is 2.0V. Your new reference is too low for the chip.


I want to be able to upload a batch of tweets to a twitter bot to be qued' for tweeting I have built a twitter bot with my Arduino and an Ethernet shield
right now, the way to make it tweet something is to manually add a phase into the code and upload it to the board for each new tweet,

I would like to create a simple way of scrolling through a queue of phrases and tweeting each consecutive one after a given amount of time (several hours).
the issue I'm seeing is that, the code needs to rerun for each tweet, and I can't figure out what needs to be in what loop. Also the entire thing needs to delay for 3.6e^6(1 hour) milliseconds (the code takes delays in milliseconds) so that I don't spam the feed,
the twitter for this project is @ether_bot.

Code is below:

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

/*
void speech()
{
  //this is where i would put the que of tweets
}
*/

// the next three lines connect the ethernet shield to the local network and establish a link with the twitter account
byte ip[] = { 192,168,1,104 };
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEU }; //address for the shield
Twitter twitter("2790106893-5ljE7WPyyGe16SqTMEm8CN5gpwDquhGnyjH2TCM");
char msg[] = "hello again, im getting some major work done soon!"; // message to tweet

void setup()
{
  delay(30000);
  Ethernet.begin(mac, ip);  // makes the connection
  Serial.begin(9600); //opens a serial interface similar to the prnt window in bluejay
}

void loop()
{
  Serial.println("connecting ...");

  if (twitter.post(msg))
  {
    int status = twitter.wait();

    if (status == 200)
    {
      Serial.println("OK.");
    }
    else
    {
      Serial.print("failed : code ");  //stuff happens here idk
      Serial.println(status);
    }
  }
  else
  {
    Serial.println("connection failed.");
  }

  do {} while(1);
}

First create an array of all the messages:

#define NUM_MESSAGES 3
const char *msg[NUM_MESSAGES] = {
    "This is the first message",
    "This is the second",
    "Third time lucky" };
int msg_num = 0;

Then in the loop, switch between messages and add a delay

void loop()
{
  Serial.println("connecting ...");
  if (twitter.post(*msg[msg_num]))
  {
    int status = twitter.wait();
    if (status == 200)
    {
      Serial.println("OK.");
    }
    else
    {
      Serial.print("failed : code ");  //stuff happens here idk
      Serial.println(status);
    }
  }
  else
  {
    Serial.println("connection failed.");
  }

  //Next message
  msg_num++;
  if (msg_num >= NUM_MESSAGES) msg_num = 0;
  delay(1000*60*60);
}


Arduino Uno: Pullup Resistor I have been reading a bit about the internal pullup resistor. I know from past projects in school that resistor themselves are fragile (burnt one by accident due to higher current than was made for).

I have two different Arduino models. One by Intel and rest are standard Arduino Uno.

So I was wondering about safely using the internal pullup resistor on the Arduino Uno. Hence my question is about the internal pullup resistor pinmode; How many pin can you connect to it safely and not overload it?

Each pin has its own, separate, pullup resistor.

I don't believe you can damage it by drawing current from the port, because the pullup resistor is only active when the port is in high impedance (hi-Z, input) mode.

The pullup resistor can be damaged by overvoltage, static discharge, and the like.

The Uno has 20 kOhm pullup resistors according to this tutorial. If you feed it a 0V signal while the Atmega is running at 5V, the current will be a quarter of a milliamp, which is miniscule.


How to program a BSFrance LoRA32u4 from Arduine IDE 8.5? I've bought a BSFrance LoRA32u4 from DIYmall on eBay UK.

https://bsfrance.fr/lora-long-range/1311-BSFrance-LoRa32u4-1KM-Long-Range-Board-Based-Atmega32u4-433MHz-LoRA-RA02-Module.html

I've copied the "bsfrance" directory (from the ZIP) into Arduino/hardware (on 64-bit Ubuntu 16.04).

Staring the Arduino IDE, I've selected the correct board (Tools>>Board>>BSFrance>>LoRA32u4).

I've selected the correct port Tools>>Port>>/dev/ttyACM1 (LoRA32u4).

Verifying a trivial sketch looks fine:

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

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

Result:

Sketch uses 4104 bytes (14%) of program storage space. Maximum is 28672 bytes.
Global variables use 149 bytes of dynamic memory.

The USB device appears in lsusb as: Bus 002 Device 077: ID 239a:800c.

Clicking install causes a white LED to flicker for around ten seconds, but results in:

avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

or:

Couldn't find a Board on the selected port. Check that you have the
correct port selected.  If it is correct, try pressing the board's reset
button after initiating the upload.

or:

Found programmer: Id = "CATERIN"; type =

or:

Device code: 0x0d

or:

.   Software Version = 1.0; Hardware Version =

or:

An error occurred while uploading the sketch

How do I transfer code onto this board?

(I am new to Arduino, so I may be missing something obvious.  I do have lots of experience programming vanilla ATMEGAs in C without the Arduino IDE.)

--

I have an AVRISP mkII - would burning a new boot-loader help, or just wreck the USB-serial on the device?

I've had the same problem, but couldn't fix it with the "Upload using programmer".
Instead i sound that the problem was that the serial connection kept dropping after a couple of seconds. My colleague, also on Ubuntu, had the same issue.

This fixed it for me: https://learn.adafruit.com/adafruit-arduino-ide-setup/linux-setup#udev-rules

The board registers as an Adafruit board on my system, and apparently the ModemManager is not too keen on that.

After running first command in the link and restarting, i could upload to the board from Arduino IDE with no errors.


Is checking an if statement every loop/while iteration inefficient? I have code that changes a bool only time in the setup(), and in my loop() I have

if (setupBool) {
// ...
} else {
// ...
}

Is checking the bool every loop slower than having a while(true) with the same code?

And what about checking it in every loop in a while(true)?

Is there any reason I shouldn't do those?

Of course an if statement cost time, although very little. However, it changes (although once), so if you need to vary depending on the value, you have to use the if statement.

A while(true) also cost a little time (a little bit less), but less than 1 us, same as the if statement. You can do perfectly do an if statement within the while(true), but remember, the loop itself is behaving like a while(true) already.

However, I wouldn't concern at all about optimizing performance, unless:

You know beforehand you will need the fastest code possible
You have already performance issues

Always prefer readability/maintainability about performance.


Power arduino from 5v rail of pc molex I'm building a small device using arduino that should be connected to my pc via a usb header to exchange data with the PC.

What I'd like to achieve is that arduino turns on when the pc is on, whereas it shuts down when the pc is turned off. If I rely on the usb port to provide power to the arduino that might not happen, since some motherboards still provide power to the usb connections even when the pc is off.

Therefore I'd like to power the arduino using the 5v rail directly from a Molex. I know that theoretically I can connect that rail straight to the 5v pin, but what about power spikes? How can I be sure that the 5v input voltage is properly filtered and stabilized? Would it be better to use a LM317 and transform the 12v rail into 7.5v to feed arduino from the vin?

The 5v of an ATX power supply will be perfectly adequate for powering an Arduino.

It will already be very heavily filtered and stabilised.


Can't write to serial immediately from PC to Arduino nano via pl2303 usb to ttl converter Goal:

I am trying to send some characters to Arduino through serial from PC via a Prolific PL2303 USB to TTL converter(Chinese clone).

I have wrote a simple sketch(attached bellow) which should light up the LED if 'n' is found or should switch the LED off if 'f' is found from serial.

What's Happening:

I opened up the serial monitor. Send a character(say 'n' which should light up the LED). But nothing happened though the RX/TX LEDs flashed. Then I re opened the serial monitor. And just after re opening the serial monitor LED light up! Every time when I issue a character from serial monitor nothing happens. But just after re opening the monitor character is sent.

H/W Connection:

Arduino Vin -> LiPo positive rail(+11V)
Arduino GND -> LiPo negative rail(GND)
Prolific GND -> Arduino GND
Prolific RX -> Arduino TX
Prolific TX -> Arduino RX

Arduino Sketch:

int led = 13;

void setup() {
  // put your setup code here, to run once:
  pinMode(led, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available() > 0){
    char bytesReceived = Serial.read();
    Serial.println(bytesReceived);

    if(bytesReceived == 'n'){
      digitalWrite(led, HIGH);
    }
    else if(bytesReceived == 'f'){
      digitalWrite(led, LOW);
    }
  }
}

Additional Notes:

Platform Windows 10
Installed Prolific PL2303 driver from here
This code is working using USB cable provided with Arduino.(I need longer cable)

Can't understand why this strange thing is happening. Any kind of help will be appreciated.

Thanks!

I have experienced similar behavior with clone chips. What worked for me is using ferrite choked USB cables similar to these; as you referenced as well, I observed that the problem occurs with either longer cable, or with cables without ferrite chokes on them. This might have to do with the PCB or the cheap chips being prone to electromagnetic interference.


Changing Baud Rate not working I have copied this code from Github :

 #include <Wire.h>
 #include <MPU6050.h>

MPU6050 mpu;

// Timers
unsigned long timer = 0;
float timeStep = 0.01;

// Pitch, Roll and Yaw values
float pitch = 0;
float roll = 0;
float yaw = 0;

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

    // Initialize MPU6050
    while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
    {
         //Serial.println("Could not find a valid MPU6050 sensor, check
               wiring!");
     }

     // Calibrate gyroscope. The calibration must be at rest.
     // If you don't want calibrate, comment this line.
    //mpu.calibrateGyro();

     // Set threshold sensivty. Default 3.
     // If you don't want use threshold, comment this line or set 0.
      mpu.setThreshold(1);
   }

   void loop()
      {
       timer = millis();

      // Read normalized values
     Vector norm = mpu.readNormalizeGyro();

     // Calculate Pitch, Roll and Yaw
      pitch = pitch + norm.YAxis * timeStep;
       roll = roll + norm.XAxis * timeStep;
       yaw = yaw + norm.ZAxis * timeStep;

         // Output raw
      //Serial.print(" Pitch = ");
         Serial.print(pitch);
           Serial.print(":");
        //Serial.print(" Roll = ");
     Serial.print(roll);
        Serial.print(":");
       //Serial.print(" Yaw = ");
        Serial.println(yaw);

           // Wait to full timeStep period
      delay((timeStep*1000) - (millis() - timer));
     }

Now the question is, whenever I try to change the baud rate Serial Monitor becomes empty.

How can this be resolved?

Some screen-shots :

Stuck!!!

You are not very much clear but these are the possible reasons for your problem.

You are using a while loop in your setup() function in your code. Your code might get stuck in there that's why you are not able to see pitch and roll. Try removing comment from the Serial.begin function over there.
After Changing baudrate in your code please make sure you are changing it on your serial monitor as well.


Arduino Uno rev 3 toggling a 230 V submersible pump on intervals I am software programmer and hobby farmer. While I was working on a hydroponic farming stuff, I had to use submersible pumps with timers. I don't want to buy timers that are actually a tedious scheduling process. so I am making one myself.

I want to toggle 230 V for turning a submersible pump(150-230 V and 18 W) ON/OFF. I read that Arduino may not able to supply enough input current that the relay requires. I am not sure about what transistor to use to amplify the input current. I came across a circuit diagram and a relay board. Do I still need to use a transistor and diode if I use this relay with an Arduino?

This is the two-channel relay I am about to use and the circuit is below.

Should I follow the circuit if I am using this relay? The relay has a tolerance of 250 V. What if the voltage fluctuates above 250 V? I am going to use a 9 V battery to power the Arduino. Feel free to explain anything that I may have to know.

UPDATE

Thanks marla for making it clear that I don't need diodes and transistors. Andy, as you said, I can't keep changing batteries often, and it will limit the system. Shall I use an adapter which reads output 5 V and 1 amperes? Will that drive the Arduino and be sufficient for both the relays?

The Arduino will easily drive this relay board, and it needs only a very small input current.

The board you linked to has a built-in optical isolation circuit, so there is no direct electrical connection between the Arduino-side of the circuit and the relay side. This should protect your Arduino if something goes wrong. For what it's worth, the product description specifies this board is suitable for "AC [...] appliances such as [...] motors". A pump is primarily a motor.

The voltage may fluctuate when the pump is started and stopped (Back-EMF). It's hard to say what this might do to the relay board if it goes way over specification. Perhaps you might be happier with a much more robust solid-state relay (SSR) that has a higher rating than the target load. Something
like SSR-25DA 25A Solid State Relay - White. Since solid-state relays are non-mechanical, they will not wear-out from repeated switching either.

You may also want to build some fail-safe sensors into your project. For example, water level float switches for both high-water and low-water marks.


Can I use this power supply with my Arduino? I am new to Arduino and electronics in general.

I am working on a project where I would ultimately like to power the project from 220V AC (Wall light switch) (I want to replace the light switch with one of my own design).

I will want to feed power to the arduino directly from the 220V connecting wires in the light switch cavity.

This power source is 5V (I know the Arduino needs 9-12V), but I will use a USB connector, wired onto my AC/DC power source, to power the Arduino.

Power Source

Ratings:

AC85 - 264V or  DC110 - 370V wide voltage input
DC 5V(+/ -0.2V) 600mA isolated output
Input Current: 0.0273A/115VAC  0.014A/230VAC
Input surge current: 20A (230VAC)
Frequency range: 50/60 Hz
Operating Temperature: -30 - 70 ℃
Relative humidity: 20%- 90%
Rated power: 3W
Output efficiency: 80%

I don't really know why yet (this is part of figuring that out), but I have the feeling that the arduino would want a linear power source, rather than a switching power source. (Because linear is cleaner power?)

Regardless, I am asking the question as if this power source will do the job, and if not, why not? (Why not a switching PSU) ?

Yes, that power supply is ideal for powering an Arduino (an Arduino doesn't care if it's linear or switching, and a linear regulator that goes from 220V to 5V is called a furnace, and you don't want one of those...)

HOWEVER unless you have a very strange wiring setup in your house, under normal circumstances there is no 220V supply in the switch.  You normally have live in, switched live out and NO neutral connection.

That means you don't have the connections you need to wire your power supply up to.

By the way: if you didn't already know that then you are not qualified to mess around with home wiring and you should leave it to the professionals.


How do I program a non-Atmel chip with the Arduino IDE? I have been working with Ardiono and esp8266 to develop a IOT project. Everything is going perfect.

Now I want to make use of a new chip i.e. the High-Flying SIP120 WiFi chip.

But I dont know how to make this chip support my Arduino code.

I have multiple big codes written using Arduino libraries and Arduino IDE already.

Any Help is appreciated. Thank you.

The question is actually very broad as there are many possible embedded processor to choose from.  Any answer would have to be presented using general terms.

As stated by @Majenko, your 1st step is to use a popular programming language that has been ported to many embedded processors (or the processor of interest).

The next step is not so clear.  When programming in the Arduino paradigm you have been using supporting C++ source code (which "Sketch" writers are calling "Libraries") that normally interact directly with the Arduino's hardware.

It is important to say this is an Arduino paradigm which has already been ported to a number of different processor.  Perhaps it is worth your time to discover which processors this paradigm has already extended to.

In the world outside of the Arduino paradigm, many embedded processor manufactures support sales of their hardware by supplying developers with tools.  Normally this includes a compiler and some software to abstract the hardware making it easier to use the more generic features.  If the processor comes on an "evaluation board" and the supporting software takes advantage of this the supporting software can be referred to a Board Support Package or BSP.

However, most will find the difference between Arduino Libraries and BSPs as vast.  Why?  Because most will write Arduino Libraries to mimic highly abstracted programming language features but in a very specific / inflexible way.  For example, a Sketch writer only has about a dozen ways to print something out.  Where as in real C, the print statement is very complex and flexible. Outside the Arduino paradigm (where the vast majority of embedded processors are used), the BSP approach is preferred as it exposes all the benefits the processor's hardware has to offer.

Where does this leave you?

The easiest approach is to find an Arduino platform which meets your needs.  Where someone has already done the work of porting all, most or some of the Arduino Libraries.

The next easiest approach would be to learn C++ and port the Arduino Library (which are really C++ classes) you are using in your program for the platform you are targeting.  Note that, in this case, it is suggested that creating an ordinary C / C++ program (abandoning the Arduino Sketch / Library paradigm) and using the supplied BSP (or other supporting software) would be easier than porting the entire Arduino Paradigm to the new platform.

The hardest approach (but the community would likely appreciate your efforts) is to port the entire Arduino paradigm to the new platform.


Convert my if loop code into a switch/case statement I have made a project where in photosensors constantly read value and if laser is cut by external object, then it beeps the buzzer.

A switch case would make it easy, as suggested by some people.
I have written my short code below, can you kindly help me change it?

Converting all if loops into a switch/case statement.

 int sensorPin = A0;
 int sensorPin1 = A1;
 int sensorPin2 = A2;
 int sensorPin3 =  A3;
 int sensorValue0 = 0;
 int sensorValue1 = 0;
 int sensorValue2 = 0;
 int sensorValue3 = 0;
 const int BUZZER = 9;
 const int BUZZER1 = 7;
 const int BUZZER2 = 8;
 const int BUZZER3 = 5;

void setup() {
 Serial.begin(9600);
 pinMode(BUZZER, OUTPUT);
 pinMode(BUZZER1, OUTPUT);
 pinMode(BUZZER2, OUTPUT);
 pinMode(BUZZER3, OUTPUT);
 // put your setup code here, to run once:
}

void loop() {
  sensorValue0 = analogRead(sensorPin);
  sensorValue1 = analogRead(sensorPin1);
  sensorValue2 = analogRead(sensorPin2);
  sensorValue3 = analogRead(sensorPin3);
  Serial.println(sensorValue0);
  delay(100);

  if (sensorValue0>920)
   noTone(BUZZER);
  else
   tone(BUZZER, 500);

  if (sensorValue1>850)
   noTone(BUZZER1);
  else
   tone(BUZZER1, 300);

  if (sensorValue2>850)
   noTone(BUZZER2);
  else
   tone(BUZZER2, 700);
}

A switch can only select different discrete values from a single variable. Since you have multiple variables and aren't looking for discrete values you have to use if not switch.


Strange Output from DS1307 RTC I'm using a DS1307 RTC (https://www.adafruit.com/product/3296) and an Arduino mega microcontroller trying to simply set and read the time of the RTC. However, whenever I try to output anything to the Serial Monitor, I get stuff like this:

The code and the wiring is fairly straightforward which is why I'm confused. I'm just directly attaching the Vcc, GRND, SCL and SDA pins of the clock to the Arduino and using a slightly modified version of the example code as a part of the RTC library Adafruit supplied.

#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 rtc;

void setup () {
  while (!Serial); // for Leonardo/Micro/Zero

  Serial.begin(57600);
  rtc.begin();

  rtc.adjust(DateTime(2017, 11, 17, 20, 33, 0));

}

void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

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

So I know I'm doing something wrong but I'm not sure what. Any help would be hugely appreciated.

Change the baud rate to 57600, it specifies at:
    Serial.begin(57600);


Detect external ground on an input pin I am making a bike alarm for my bike. I haven't started yet.
Basically, I'm thinking of a pin to be connected to the metal post (to which the bike is locked.) I want to detect if that connection (to the ground via the metal post) is broken.
Is that possible?

How about fastening a wire to the post, and then the other end, on the bike, goes into a "jack" (the sort of thing you plug headphones into). With the wire inserted, it makes a connection, and the Arduino knows the wire is there. As the thief steals the bicycle the plug (or loose wire) is pulled from the jack, breaking the connection. i.e.


Serial: active low or active high? When I use the Mega 2560 additional serial ports, I realize that it is active low, active high. I know that TTL is active high and the serial port is obviously stated in arduino serial port page.
I also found out that the receive pin flashed (put an LED) when I typed in to the serial monitor. Is this a mistake or problem?

The Serial Class of the Arduino uses Typical usage of the Serial Ports is the USART in Async mode. Which is hard coded to IDLE state of HIGH or 1 or VCC.

http://midas.psi.ch/mscb/hardware/bits.gif
(picture wont add - so here is a link to it)

If you need to drive the TTL inverted from its traditional values, the Serial Class can not do this. However, you can use the SoftwareSerial Class and enable the inversion in the constructor

SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);

As for why would someone want to invert the TTL UART. In some cases it is possible to drive RS232 directly. As RS232 converters inverts the TTL to +12V/-12V. 5V = -12V and 0V = +12V. So depending upon the RS232 receiver, it may actually trip its TTL output  at 2.5V and not 0V. If so then using the SoftwareSerial Class with inverse logic may drive the RS232 input of another device, without requiring a RS232 transmitter on the Arduino's TXout pin.


Why the command noDisplay() clear all LCD screen? i want to preserve video information for long time without communicating with arduino on lcd 1602, i'm tryng to use the command of liquidCrystal library noDisplay() but when i use it,this clear all display. On arduino website here is the description of this command "Turns off the LCD display, without losing the text currently shown on it." but i lose all on screen. Thanks for reply

there is my test code

#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // Turn off the display:
  lcd.noDisplay();
  delay(500);
  // Turn on the display:
  lcd.display();
  delay(500);
}

with this code display blinking and don't show continuos "hello word".

I tried out your code. It's working absolutely fine.

Whenever lcd.noDisplay() executes then LCD not displaying hello, word!...
And whenever lcd.display() executes then LCD displaying hello, word!...

So, that's why "hello word" not continuously displaying.

And you can also find the display() and noDisplay() functions to turn on and off
the display comment on top of arduino sketch.


Creating linear motion using motor I am trying to make a smart lock for bicycles. This lock can be controlled with the help of smartphones. For the purpose, I am using an Arduino interfaced with HC-05 Bluetooth Module which receive commands from an Android smartphone.

The overall project is almost over, except the actual lock. I want to create a lock with a pin which can be slide between the spokes of the wheel to cease the motion of the wheels. I can't find any product in the Indian market. Can you please suggest any product available or how to make one myself?

  I've seen the solenoid locks but their stroke is too small to make a meaningful lock out of it.

Your help will be well appreciated.

The pin that slides between the spokes should be just a metal bar that accepts your "small" pins in the ends to hold it in place.  Try looking at it from a different perspective and I think you will find a lot more suitable products.

You could use a worm gear, but this would be susceptible to bruit force attacks (literally) and would be easier to break.

Have you considered what happens when the power fails?  Does the lock lock or unlock?  If it unlocks on a power fail then it will be quite easy to open.  If it remains locked on a power fail then its not very user friendly, you would have to carry spare batteries and changing tools with you.

Sorry, but it is easy to poke holes in other peoples designs.


A confusing condition statements I am working on a project in making a timer socket using Arduino and a current sensor. For the code I decided to modify a code that was meant to be a kitchen timer.

In that code I found a statement

currentMode = currentMode == MODE_IDLE ? MODE_RUNNING : MODE_IDLE;

I assumed this works in a way that it chose whether the timer is in the current mode or the idle mode but I don’t understand the mechanism behind it.
What does this statement mean?

Assuming you understand how the ternary operator works, the statement is simply toggling the currentmode between its two possible settings.

if you do not understand ternary operators, it can be re-written as:

if (currentMode == MODE_IDLE) {
  currentMode = MODE_RUNNING;
} else {
  currentMode = MODE_IDLE;
}

You should read up on the ternary operator.  It appears in several languages in various formats and can come in handy in a variety of situations.

In general terms the ternary operator is of the following form (as used in an assignment):

result = (booleanExpression) ? (value if true) : (value if false);

but you can use it in other contexts for example in a function call:

someFn(booleanExpression ? trueValue : falseValue);


Arduino Blocks at Uploading I am trying to make an operating hours counter with arduino, i started with a basic script to make the arduino work as a stop watch, This is my script:

unsigned long start=0, finish=0, elapsed=0;

 void setup() {
 Serial.begin(9600);
 Serial.println("Clock START");
 }
 void displayResult(unsigned long elapsed){
   float h,m,s,ms;
   unsigned long over;
   h=int(elapsed/3600000);
   over=elapsed%3600000;
   m=int(over/60000);
   over=over%60000;
   s=int(over/1000);
   ms=over%1000;
   Serial.print("Elapsed time: ");
   Serial.print(h,0);
   Serial.print("h ");
   Serial.print(m,0);
   Serial.print("m ");
   Serial.print(s,0);
   Serial.print("s ");
   Serial.print(ms,0);
   Serial.println("ms");
   Serial.println();
 }

 void loop() {
   start = millis();
   delay(200);
   Serial.println("Start");
   Serial.println("doing Operations and stuff");
   delay(800);
   finish=millis();
   elapsed=finish-start;
   Serial.println("Ended !!!");
   displayResult(elapsed);

 }

Unfortuantly the arduino compiler blocks at the Uploading part, i tried compiling it at first without uploading, it gave me no warning errors. I tried compiling other scripts they worked, it only blocks for this stop watch code.
Thank you for your help

There is a bug in early versions of the Mega2560 bootloader.  It crashes on !!! (or enters some other special state that stops uploading happening).

Your string that contains !!! will be breaking it:

Serial.println("Ended !!!");

Simple solution: don't use so many exclamation marks.


Arduino Serial Response is Slow when in While Loop Good evening all,

I'm having an issue with a quick "test" project that I am tinkering with (learning the "do's" and "don'ts") the NeoPixel LED strip.  I've been piecing together excerpts from other folks and so far everything is great.

I'm doing it over serial sending switch/case with numbers from the keyboard for different options.  The issue I am currently having is "case 1:", when I hit the "1" key and it fires off, I want to be able to interrupt it immediately by using key "0".  So basically, I'd like it to loop forever after hitting key "1" but terminate after hitting "0".

However, when hitting key "1", then key "0" immediately, the while loop repeats twice, then breaks.  I haven't done any C/C++ since I was 12 and now I'm 38 so now it is all trial and error based so please pardon my syntax.  Any help would be appreciated.

#include <Adafruit_NeoPixel.h>
#include <SoftwareSerial.h>

#define PIN 6
#define LEDs 16

int LED_Fade_Interval = 5;

Adafruit_NeoPixel strip = Adafruit_NeoPixel(LEDs, PIN, NEO_GRB + NEO_KHZ800);

void setup() {

  Serial.begin(9600);

  strip.begin();
  strip.show();

}

void loop() {

  while (Serial.available() == 0);

  int numKey = Serial.read() - '0';

  uint32_t low = strip.Color(0, 0, 0);

  switch(numKey)
  {

    case 1:
      Serial.println("LED Strip is ON - BLUE FADE");
      while (numKey != 0)
      {
        int numKey = Serial.read() - '0';
        delay(50);

        ws2812_FadeInOut(0, 0, 255, LED_Fade_Interval);

        if (numKey == 0)
        {

          for( int i = 0; i<LEDs; i++){
            strip.setPixelColor(i, low);
            strip.show();
          }

          break;

        }

      }

    case 0:
      Serial.println("LED Strip is OFF");
      for( int i = 0; i<LEDs; i++){
          strip.setPixelColor(i, low);
          strip.show();
      }
      break;
   }
}

// *******************************************
// FADER Function
// *******************************************
void ws2812_FadeInOut(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }

     strip.show();
     delay(wait);
  };

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }
     strip.show();
     delay(wait);
  };
};

Serial.read() reads one character from the Serial stream, or returns -1 if there are no characters to read.

When you send a 1 from the Serial Monitor, the Arduino board first receives an Ascii 1, and then receives a line-end character (eg, an LF from Linux) or characters (eg, a CR and LF from MSWindows).

Since none of 1, CR, or LF are equal to an Ascii 0, the numkey value computed at the fourth line of case 1 is not 0, so the exit condition isn't met.  Thus the fade loop continues running, until it sees a 0 character.

Instead of continuing to read characters within while loops within the switch/case statement, test if more serial input is available.  Note, avoid exiting early from case 1, after you read a digit at the beginning of loop(), read and discard the line-ending characters that follow.


SD datalogger sometimes skips readings I'm using the Adafruit SD shield with a Mega board and wrote a simple program to log data.  I am outputting a constant stream of data at 115200 baudrate from another Arduino to the Mega.  The data output is mostly good, but there are places where some data are skipped.  These skipped data usually occurs around a file flush.  I've tried playing around with the flush frequency and the soft buffer size, but to no avail.  I'm not sure what these hiccups are caused by and would like some help.

void loop(void)
{
  while (Serial1.available())
  {
    softBuffer[i] = Serial1.read();
    i++;
  }

  if (i >= SOFT_BUFFER_SIZE)
  {
    for (x = 0; x < SOFT_BUFFER_SIZE; x++)
    {
      logfile.print(softBuffer[x]);
    }

    logfile.flush();

    i = 0;
  }
}

The SD card library works by filling up a 512 byte buffer. Once full, the data is written to disk.

The flush command updates the directory listing with the correct size for the file and also updates the file allocation table. It only needs to be done once, just before you pull the card out.

While flush is doing its thing, the internal serial buffer of the Arduino is filling up with new bytes. The internal buffer is 64 bytes long so if flush takes too long, the internal buffer fills up and you lose characters. You could edit HardwareSerial.cpp in the Arduino program directory to make it say 256 bytes.

Because of this softBuffer is not needed. Simply write straight to the card and let the internal buffer handle the buffering. See https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/HardwareSerial.cpp for the Serial code.

unsigned long bytesWritten = 0;
void loop(void)
{
  while (Serial1.available())
  {
    logfile.write(Serial1.read());
    bytesWritten++;
    if(bytesWritten > BYTES_PER_FLUSH) logfile.flush();
  }
}


Servo motor activation with pressure sensor I need to run my servo motor within a specific pressure range, given by a pressure sensor. I don't understand how to code this. I have coded for servo motor movement but I need to activate that movement in a specific range. Please, help me.

This is my servo code:

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // twelve servo objects can be created on most boards
int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);
  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for(pos = 0; pos <= 30; pos += 1) {
    // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);
    // tell servo to go to position in variable 'pos'
    delay(5); // waits 15ms for the servo to reach the position
  }
  for(pos = 30; pos>=0; pos-=1) {
    // goes from 180 degrees to 0 degrees
    myservo.write(pos);
    // tell servo to go to position in variable 'pos'
    delay(5);
    // waits 15ms for the servo to reach the position
  }
  delay(1500);
}

I need to activate this servo within a 10-70 pressure range.

You don't tell what pressure sensor are you using, but suppose that a call to readPressure() will give as pressure as an int

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup()
{
    myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
    int pressure = readPressure();

    if(pressure >= 10 && pressure <= 70) {
        //  Pressure is in range. Move the servo.
        for(pos = 0; pos <= 30; pos += 1) { // goes from 0 degrees to 180 degrees
            // in steps of 1 degree
            myservo.write(pos);              // tell servo to go to position in variable 'pos'
            delay(5);                       // waits 15ms for the servo to reach the position
        }

        for(pos = 30; pos>=0; pos-=1) {   // goes from 180 degrees to 0 degrees
            myservo.write(pos);              // tell servo to go to position in variable 'pos'
            delay(5);                       // waits 15ms for the servo to reach the position
        }
    }

    //  Wait for another 1.5 sec before next loop().
    delay(1500);
}

Of course, you have to complete the code with the actual sensor calls.


Suddently, "avrdude: Device signature = 0x000000" with ArduinoISP. Is my chip dead? I have some boards with the atmega32u4 that they were working perfectly before. I'm using an unnoficial UNO board to program them via ICSP. To power the uC I'm using two lithium batteries and a step-down converter to drop it to 5 V.

This started happening when I tried to upload code via ISCP when the target chip was not powered by mistake.

This is my error message:

Arduino: 1.8.5 (Windows 10), Placa:"Arduino Leonardo"

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

     Using Port                    : COM4
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

What I've already tried:

Different programmer (another Uno board);
Uploading to a proper Leonardo board via ICSP, it worked;
Uploading to another of my boards via ICSP, it worked;
Running with the portable Arduino version;
Check if the chip is being powered with 5 V;
Changed wires and checked the connections;
The chip does not get hot;

I've been around this two days straight, any help would be much appreciated.

Mostly this error is due to connections/powering issues (as already mentioned in your output ).

Check connections, especially power and ground also check the
resistance between Vcc and GND of your target MCU. (If it's less than
100ohm that means something is off in your circuitry or your MCU is
already fried.)
Check if your MCU is actually getting enough power (voltage and current) also check if it's getting excess voltage.
Make sure there is proper "common grounding" done between devices.
If you are sure that the above points are checked and you still get the error try the override flag -F (avrdude through shell/command-line) and if you are still not able to upload try the manually changing the address (not recommended ) in your arduino's library so that it matches with the signature it's receiving.
Finally try using a direct USB interface with atmega32u4 as atmega32u4 supports it and upload the bootloader again through an old software called Flip after that try again.

After all this if you are not able to upload then probably your MCU is dead and it might be due to an unnoticed wrong power connection or short circuit or unintentional fuse reconfiguration (highly unlikely).


Is it possible to gather data while the Arduino is being powered with a battery, connect to comp, and then read off the values in Serial Monitor? I want to do a project where I gather data such as sunlight hours per day, as well as temperature highs/lows. Once I have gathered 24 hours worth of data, I want to hook it up to the computer to read off the values in Serial monitor.
When I try and open the Serial monitor, it restarts the program wiping all the memory.
I tried doing something with PROGMEM, but that didn't seem to help as it is only for constants.
I want to avoid using an LCD to display data if possible.

Yes, this is perfectly possible. You will need to write a routine that you can trigger via Serial. For example you will listen on Serial until you get the dump command. Then run a function that spits your variables out to Serial.
You just have to be careful where you save your 5 variables.
If stored in memory (RAM), you should avoid power loss. Therefore I'd suggest a FTDI USB-to-Serial adapter. There you just connect the TX, RX and GND wires and proceed with the Arduino IDE's Serial Monitor.
If stored in EEPROM, you can use the regular USB connector of Arduino.


Data type conversion problem I have a Wemos D1 board with a OLED display using the u8g2 library.

I am printing my MAC-adress on the serial port & would like to print the same information on the OLED:

#include <ESP8266WiFi.h>
#include <U8g2lib.h>
byte mac[6];
setup(){
  Serial.println(WiFi.macAddress());
  WiFi.macAddress(mac);
  u8g2.drawStr(1,10,WiFi.macAddress());
  u8g2.sendBuffer();
}

This does not work. It prints the MAC-address on the serial port but not on the OLED.

I get: no known conversion for argument 3 from 'String' to 'const char*

How can I print the MAC-information on my oled using the u8g2-library?

As said by @Mikael Patel
You need to append .c_str() to u8g2.drawStr(1,10,WiFi.macAddress()); creating the line: u8g2.drawStr(1,10,WiFi.macAddress().c_str());

The problem is that WiFi.macAddress() returns a String not the needed const char* by the drawStr function. c_str converts the String object into a const char*.

Please look at the documentation of the u8g2 library for the drawStr function.

link

And here the documentation for String

link


I2C Interrupting Loop? Imagine i have a code, that loops, and at one point there is i2c request.

Is loop() paused right away when there is Wire.onReceive() or loop is finished then Wire.onReceive() is called?

The onReceive callback is called from an interrupt service routine (ISR). As the name says, interrupts are "interrupting" the currently executing code almost immediately. And "almost immediately" means that it only will take a few clock cycles. (This is the reason why changing data in an ISR can corrupt data, since the ISR may change a variable, when the main code tries to read it)

So the Arduino will not wait for the loop() function to end. It will interrupt in the line, where it was when the interrupt occured, and return to it after the ISR returns.


Understanding how a tilt switch works I am learning Arduino and pardon me if this is nooby. I am trying to make an LED glow when the tilt switch is tilted. The LED should not glow if the tilt is in normal position. The circuit and the code are in the attached image.

Based on my understanding of the code, I thought that when the tilt switch pin 5 is passed with HIGH signal from 5V the IF condition gets satisfied and tje LED on pin 13 would glow.

But it does not happen. The LED just glows before I tilt the tilt switch. Could you please clarify/correct my mistake. Thank you.

Attaching the code below as per suggestion

int ledPin = 13;
int switchPin = 5;

void setup() {
  pinMode(ledPin,OUTPUT);
  pinMode(switchPin,INPUT);
}

void loop() {
  Serial.begin(9600);
  if (digitalRead(switchPin) == HIGH) {
    digitalWrite(ledPin,HIGH);
    Serial.print("we are here");
  }
  if (digitalRead(switchPin) == LOW) {
    digitalWrite(ledPin,LOW);
    Serial.print("there");
  }
}

Understanding how PULLUP works lead to the solution. Also learnt that switches are supposed to be connected to ground. Thank you all for your time. Especially chrisl.


How can I convert Arduino String to C string type? I got a String which as I understand is an Arduino object, and got some C++ code:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <string.h>

LiquidCrystal_I2C lcd(0x20,16,2);

boolean borrar = false;
String IP;

void setup()
{
  lcd.init();
  lcd.backlight();
  pinMode(13,OUTPUT);
  Serial.begin(9600);
  Serial1.begin(9600);

}

void loop() {

  while (Serial1.available()) {

    char caracter = Serial1.read(); //Comprobamos el caracter

    switch(caracter) {

    default:
                if (borrar) {
                              IP = "";
                              lcd.clear();
                }

                lcd.print(caracter);
                delay(125);
                borrar = false;

                IP.concat(caracter);
                break;

    case '\r':
    case 0x0F:
    case 0x0A:

                String res = "";
                borrar = true;
                int num= atoi(IP.c_str());
                if (num < 127)
                  res="Clase A";
                if (num == 127)
                  res="Direccion reservada";
                if (num > 127 && num < 192)
                  res="Clase B ";
                if (num >= 192 && num < 224)
                  res="Clase C ";
                if (num >= 224 && num < 240)
                  res="Clase D ";
                if (num >= 240 && num < 255)
                  res="Clase E ";
                break;

  } //fin switch

}//serial disponible

}//fin programa

However, this won't compile because of this line:

int num= atoi(IP.c_str())

As IP is a String and such method works for string. How can I make it compatible (convert it)?

Try

unsigned char z[100];
IP.getBytes(z, 100);
z[IP.length()] = 0;
int n = atoi(z);

To retrieve bytes inside the string. This assumes IP string's length is shorter than 100.


Arduino Nano and SIM800L on Battery Power I'm very new to Arduino and everything related but I'm highly interested to learn more. However, I've run into a problem right in the beginning.

I want to build some sort of portable emergency/notification button. One pushes the button and an SMS is sent or an HTTP call made to a server. I want to base this project on the Arduino Nano as it's quite small and therefore easily transportable. To have GSM/GPRS connectivity I found the SIM800L which seems quite suitable to what I have in mind. Now to the big question, how to power the Arduino Nano as well as the SIM800L on an portable power source, preferrably only one power source.
From my understanding, the SIM800L requires a peak current of 2A when doing handshakes and sending signals. Is there any way I can power the SIM800L through the Arduino Nano, like Battery -> Arduino Nano -> SIM800L, or do I need to connect both the Arduino Nano and the SIM800L to the battery?
Regarding the lifespan, for now it would be sufficient if I could press the button a few times and afterwards it'd stop working.

Check out

  Thin battery to power arduino micro with nRF8001?

Also, I found a 6v battery (A544) at Menards that is about the same diameter as a AA, but is considerably shorter. It has 178 mAh capacity.

I haven't taken the time to test it, but I would guess it wouldn't have as much of a temperature issue.

It's not as small as the CR2032 in the above mentioned link, nor is it flat, but it's an option.

You might consider an Arduino Beetle. They are really super incredibly tiny and still 16mHz. I can't get any more info from where I'm at, but I'd believe they would use even less power than a Nano/Micro.

I found an Instructable that shows how to use a Beetle, a rechargeable 3.7v LiPo battery, and an HC-06 Bluetooth module. Sounds like it's equivalent to what you're looking for.

http://www.instructables.com/id/Beetle-Minimize-Your-Arduino-Projects/