Unable to upload sketch to Leonardo I'm really at my wits end. For a couple of hours I have been programming a custom board that uses everything as on the Arduino Leonardo. A few hours ago I am not able to upload anymore.

I get the following error:

   avrdude: error: buffered memory access not supported.
   Maybe it isn't a butterfly/AVR109 but a AVR910 device?

I've tried everything from re-installing the IDE, re-installing the board in Device Manager, changing the COM Port. I really just don't know anymore.

Here is some more data that might be relevant or useful:

     Using Port                     :\\.\COM6
     Using Programmer              : avr109
     Overriding Baud Rate          : 57600
     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

[EDIT]
I've now checked the battery (yes with a multimeter), it is fully charged, as it charges when the USB is connected. I've also tried a different computer, along with a different USB cable.

Try this:

First: you must find the COMx used for your "Arduino Leonardo" in the "Device Manager" of Windows.

Second: make double click to see the properties of the device, and go to the "Port configuration tab"

Third: enter in "Avanced Options" and deactivate "Use FIFO buffers", and accept all changes.


Why did my pushbutton LED circuit work when my wiring was wrong? I had a Coursera Arduino homewhere wherein you create a simple pushbutton-controlled LED circuit.

I used the example "button.ino" script that's builtin to the Arduino IDE, without modification. I'll reproduce it at the end of this question.

Here's what I did (wrong):

My circuit went from 5V Power to the top pin of a push button. The bottom of the pushbutton was (correctly) wired to Pin 2 on one side and a resistor was used to wire the other bottom pin to the anode of LED. The cathode of the LED was wired to ground.

The reason I think this is wrong is that I forgot that I was supposed to wire the LED to a pin corresponding to ledPin in the example script. The example script uses Pin 13, which has the builtin LED. I was using an external LED. Yet, the circuit worked perfectly.

Why did it work? Doesn't that mean the 5V power output was getting turned off (I'd guess you call that being set to LOW) when Pin 13 was set to LOW? Why would that be the case?

/*
  Button

 Turns on and off a light emitting diode(LED) connected to digital
 pin 13, when pressing a pushbutton attached to pin 2.

 The circuit:
 * LED attached from pin 13 to ground
 * pushbutton attached to pin 2 from +5V
 * 10K resistor attached to pin 2 from ground

 * Note: on most Arduinos there is already an LED on the board
 attached to pin 13.

 created 2005
 by DojoDave <http://www.0j0.org>
 modified 30 Aug 2011
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/Button
 */

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  }
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

The LED wired to the push button was turned ON by the push button closing the circuit, without any intervention from the micro controller.
That's a pretty simple circuit: a voltage source, a switch, an LED and a resistor, all in series. When you close the circuit the LED turns on. Simple.

The code on your microcontroller is watching the state change on the button and turning ON/OFF the on board LED: it has nothing to do with the LED in your circuit/breadboard.


Trying to print text on LCD display from Arduino trinket I'm trying to simply program an Arduino trinket to display some text on an LCD display.

I'm basically trying to follow this, except connect it to a Trinket rather than an Arduino Uno. The background color of the LCD display is changing as expected from the loop function in my Arduino code, but it's just displaying some o's and arrow's for text on the LCD display.

I'm new to Arduino's (and EE in general), but am a computer programmer.

What am I doing wrong that the sample code in the above link doesn't print text on my LCD display?

Warning: I do not have a ATtiny85 nor the lcd so this is purely based on what I found after some reading up on this mcu.

What I would do in your situation:
As the trinket is using a ATtiny85 it does not have hardware serial. So a software variant is needed.
You opted for software serial (which is the most obvous in Arduino world) but which seems to be the hardest solution.
According to this source Serial communication with the Tiny's is is possible (And I quote)

  you might have to tune the internal oscillator to get a stable
  connection.

Assuming your lcd does not need to send data back; I would try the TinyDebugSerial.


Control Arduino through ethernet. How to contact from outside network and securely I'm new to Arduino so please bear with me if my question is too simple or broad (I did try and research it) or guide me if it belongs elsewhere (networking forum?)

I would like to be able to control my Arduino remotely.  By remotely, I mean I would like to be able to access it over the internet.  I've done some research and know about the Arduino Ethernet Sheild (see:  How can I connect to an Arduino using WiFi?)

But I'm a newbie and it's not clear to me how I'm going to make my device "discoverable" from outside my local network.  I gather it involves "opening a port on my router"  Can someone expand on this or provide an example/tutorial? If I can do this, it would also be nice if there was some security so that not just anyone could control my robotic killer dog or whatever :).  I would think these are both common desires,  and there is probably tons of material (maybe even tutorials) but perhaps because I'm new to Arduino, I'm having a hard time finding material.

I thought a nice first step would be to have my Arduino Uno board connected to a single LED.  If I could then have a simple webservice on it, I could connect via my phone from work with a http post request.  Of course, I'd need someone at home to verify the led went on/off (or set up a camera for remote access).

Let me know if I can provide more detail or clarifications.  And Thank you!

Dave

The easiest way to do this is to use Blynk, an Internet Of Things (IoT) web service that includes an Arduino library, apps for iOS and Android, and a central server that the smartphone app and the Arduino both connect to. Since both connections are outgoing (and matched up by the Blynk server), each one works just fine from behind NAT routers without any ports needing forwarding. See Blynk's demo video for how to create a basic working app in 5 minutes (including your described LED controller and much more). Ok, I'll admit that starting from cold, it takes most of us a little longer than 5 minutes to get it going, especially if you like to read about and understand what you're doing as you do it. But it will still be minutes, not hours. This is the quickest, most painless way to get an IoT device up and running.

That basic app (which can read & write to ports, PWM, and A/D) is then extensible to work with your own code & hardware. The functions available lend themselves to just what you are looking to do, with the possible exception of uploading the images it takes. And the Arduino itself isn't really well suited to that task, given its memory constraints.

Update:
I use the ESP8266 like the one you linked to. They're cheap and easy to use but with a gotcha: they are 3.3v only on both power & signal lines, which can be a challenge when working with a 5v MCU board. Here's how to wire one up for a 5v Arduino. Note the dedicated 3.3v regulator; the Arduino's on-board 3.3v supply isn't sufficient for an ESP8266:

For quick & dirty, you can wire this up on a breadboard. Ultimately you'll want something more stable (mechanically) than breadboard wiring. I made up a few 5v ESPs on strip-board (aka Vector board or Vero board), but that's another project:

--

** (Disclaimer: I have no connection to the organization other than as a happy user/experimenter.)


Where are these capacitors on the arduino schematic? My arduino has these two capacitors

But I can't find any 47uf capacitors on the schematic. Is this not the value but instead a code? Where are these in the schematic?

What: Looking at the schematic that you provided, it seems likely that they serve as C6 & C7.

Why: These are shown as 100 uF each and act as "filter" capacitors for IC4, the 5V regulator.
Within certain limits, such capacitors are not critical in value, and the manufacturer has probably decided that a factor of in the capacitance is probably acceptable.
They are probably correct :-).

How to check: You can check this yourself with an Ohm-meter set to the lowest Ohm range available - often = 200 Ohms max.

Turn off power to the board and leave it off for say 5 minutes to allow capacitors to discharge.
Locate I4 and find its input and output pins or tracks leading to them. You can often get ohmic connections at vias as the tracks change board layers.
IC4 pin1 will be grounded.
One lead of C6 & C7 are also grounded.
The pad you can see in your photo on the board edge side of the caaps is probably the -ve terminals (about 99%+ likely) (and they match the can markings)
and the "stippled" surface is almost certainly system ground.

If you can confirm that the two caps are connected to ground as and where described above, then:

Apply Ohm meter probes between the non ground lead of a capacitor and each non-ground pin in turn of IC4. One of them will be a low resistance connection if they are C6 & C7. Check the other capacitor - it should connect to the other side of IC4.
Reversing the meter leads in each case may give somewhat different readings for non-hard-connected points but should be low and consistent for hard-connected by a track points.


Arduino board as USB/serial for a Nano with broken USB I broke the USB connector on an Arduino Nano and I am trying to use my Uno board as a USB/serial adapter to be able to upload sketches. The broken Nano came with a customized bootloader (avrdude -c arduino compatible), which I do not have a copy of. The content in the HEX files I have is encrypted, it has to go through the bootloader for the plain code to be flashed. This rules out ISP.

I came up with this:

Please note that the ATMega on the Uno board is removed. As I am proxying the Nano through the Uno board, I am wiring RX to RX and TX to TX.

The problem I face is that it seems the Nano board is not receiving data from the PC. Everything else works:

pressing the reset button on either board resets the Nano
TX from the Nano goes back to the PC (the current sketch on the Nano prints some stuff on boot), TX leds blink accordingly on Nano and Uno boards
RX led on the Uno board blinks when PC sends something, but RX led on the Nano board does not blink in that case
connecting the RX/TX Nano pins to a USB/serial cable lets me send and receive data to/from the sketch

I tried with another, non-broken, Nano (standard bootloader) and I have the same issue, so I think the broken Nano is fine. If I upload a sketch that continuously writes to the serial port, the PC receives it. If I upload an "echo" sketch, I do not get anything back (the "echo" works well over direct USB connection).

I am a software guy, my apologies if I am doing something obviously wrong. I read several pages on the topic, I couldn't spot a fix. The boards are not official Arduino products, but I am not sure this is relevant. I wonder if part of the answer is related to the fact that the USB/serial conversion is handled by a Mega16U2 chip rather than something like a CH340, now useless on the broken Nano.

Some links that I checked:

Arduino UNO as USB to serial TTL converter
Arduino Uno as an FTDI RS232 to Serial Adapter
Using an Arduino or Seeeduino for its FTDI chip
Use an Arduino UNO as a USB-to-Serial converter

As explained in comments by Chris Stratton, both the Mega16U2 on the Uno and the USB/serial chip on the Nano are competing for the signal level. Removing the resistors on the RX/TX lines between the USB/serial chip and the ATMega on the Nano board will prevent it from interfering with the signals exchanged with the Uno.


Arduino struggling to power a large LED strip I'm building a word clock and its a grid of 20x20 letters, each with its own LED (I know, its absurd for just a clock). I've recently got the LED's on a strip. Its the WS2812B type, just like the neopixels. There are 3 rolls of 5m strips and a single 1m strip. When I tried to power the 1m strip, everything worked perfectly and all looked quite lovely. But when I tried the 5m strip (just one of them), this happened: https://www.dropbox.com/s/5w1lok6wa7dfvzd/IMG_0046.MOV.mov?dl=0

If you didn't see the video I recorded of it, for a second or two after powering the arduino (uno) on, it works as expected but not long after it all stops the colors and fades to red, sometimes it just instantly jumps to it, like the second time in the video. I don't know what happened but all I can guess is that the arduino is not able to power the strip properly. Any ideas on what I should do to be able to power a total of 16m of these strips?

WS2812 use around 1mA when they are off. So that's already 400mA with no LED lighted. USB can supply around 500mA. So you only have 100mA available.

Each led package has three colored leds inside; Red, Green and Blue. Every color will use around 20mA when fully turned on.

So you can only turn on 5 colors at full brightness at 500mA.

Using a 2.5A supply you could go up to 105 colors, or 35 leds full white.

This would be more than enough for a word-clock, as most leds will be off.


What is the difference between a Hall effect sensor and an inductive one? From what I have read, when placed within a magnetic field, a current will flow in both sensors.

My goal is to use this kind of sensors to guide a robot thanks to an existing automower loop wire, such as suggested in DIY Perimeter Wire Generator and Sensor.

I am thus wondering what is the difference between a Hall effect sensor and an inductive one such as the one described in the link above?

First they physically work differently. In the Hall effect sensor the electrons flowing through a plate will be deflected. Thus there will be a voltage perpendicular to the current, which can be measured. The voltage will be proportional to the magnetic field strengh. So you can sense a magnet, that is near the sensor, even if it doesn't move.

For the inductive sensor you have a guiding wire, that has an AC current flowing through it. This also means, that a magnetic field ist constantly building up and collapsing again around the wire. This change of magnetic field will induce an induction voltage in a nearby wire loop (the actual sensor). The frequency of that voltage is the same as of the guidance wire and the strength depends on the distance between the wires. So you are not measuring the magnetic field strength directly, but you measure how much it is changing (mathematically you differentiate).

Two different measurement methods which can be used to do the same thing. To guide a robot over a predefined course I would use the induction method (as long as the situation allows laying out wires), since it can be made less susceptible to noise. For that you can filter out all frequencies except of the used guiding frequency with a LC circuit. Or even better (though maybe not important) a lock-in amplifier. The hall sensor is an analog device, which can be very noisy.


How can I fix this error "invalid operands of types 'const char [17]' and 'float' to binary 'operator+'"? #include <Wire.h>

long aX,aY,aZ,gX,gY,gZ;
float rtX,rtY,rtZ,gfX,gfY,gfZ;

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

void loop()
{
  recordAccelregisters();
  recordGyroregisters();
  printData();
  delay(100);
}

void setupMPU()
{

  Wire.beginTransmission(0b1101000);
  Wire.write(0x6B);
  Wire.write(0b00000000);
  Wire.endTransmission();
  Wire.beginTransmission(0b1101000);
  Wire.write(0x1B);
  Wire.write(0b00000000);
  Wire.endTransmission();
  Wire.beginTransmission(0b1101000);
  Wire.write(0x1C);
  Wire.write(0b00000000);
  Wire.endTransmission();
}

void recordAccelregisters()
{
  Wire.beginTransmission(0b1101000);
  Wire.write(0x3B);
  Wire.endTransmission();
  Wire.requestFrom(0b1101000,6);
  while(Wire.available()<6)
  {
    aX = Wire.read()<<8|Wire.read();
    aY= Wire.read()<<8|Wire.read();
    aZ = Wire.read()<<8|Wire.read();
    processAData();
  }
}

void processAData()
{
  gfX= aX/16384.0;
  gfY = aY/16384.0;
  gfZ = aZ/16384.0;
}

void recordGyroregisters()
{
  Wire.beginTransmission(0b1101000);
  Wire.write(0x43);
  Wire.endTransmission();
  Wire.requestFrom(0b110100,6);
  while(Wire.available()>6)
  {
    gX = Wire.read()<<8|Wire.read();
    gY = Wire.read()<<8|Wire.read();
    gZ = Wire.read()<<8|Wire.read();
    processGdata();
  }

}

void processGdata()
{
  rtX= gX/131.0;
  rtY = gY/131.0;
  rtZ= gZ /131.0;
}

void printData()
{
  Serial.print("Gyro degree(x)= "+ rtX + " ");// this line shows error mentioned above in the question
  Serial.print("Gyro degree(y)= "+ rtY + " ");// this line shows error mentioned above in the question
  Serial.print("Gyro degree(z)= "+ rtZ + " ");// this line shows error mentioned above in the question
  Serial.print("Accel Gforce(x)= "+ gfX + " ");// this line shows error mentioned above in the question
  Serial.print("Accel Gforce(y)= "+ gfY + " ");// this line shows error mentioned above in the question
  Serial.print("Accel Gforce(z)= "+ gfZ + " ");// this line shows error mentioned above in the question
}

this is a code of mpu6050.  Why am I getting this error and How Can I resolve it?

These lines give you errors, because you cannot simply add character arrays (aka c-strings) and floats together with the + operator. C/C++ is very strict, when it comes to variable types. The compiler does not know, how it should add these types together.

In other high level languages a string literal (characters enclosed by " in the source code) are more complex types, than c-strings. They mostly have various different methods and also an implementation of the + operator for adding a float number in human readable form. This complex type in the Arduino world is the String type. You can convert the float variable into a String and then add them together. But that's not the way, that you should do it. Strings on AVR based Arduinos (like Uno, Nano, ...) can be very evil due to the limited RAM. See Majenko's blog entry about The Evils of Arduino Strings for more information.

Instead you should just use multiple print statements. As Serial data is send out serially (one byte after another), it doesn't matter, if you put all the data to send in one print statement, or in multiple onces. So each of the offending lines can be converted to something like this:

Serial.print("Gyro degree(x)= ");
Serial.print(rtX);
Serial.print(" ");

It does exactly, what your code does. But it will not produce an error, since the Serial.print() method is also implemented for using float arguments.


arduino leonardo stops transmitting once hdmi cable is connected to a screen I am using arduino leonardo for moving mouse pointer with head tracking using MPU6050. It works fine in general. But as soon as I connect an external lcd screen to my laptop via hdmi cable, it stops transmitting. (that is the TX led goes off altogether and the mouse stops moving) I am not able to figure out what the issue is here Will using a teensy 3.0 instead of leonardo solve this problem?

The issue is that the mouse coordinates are being set by the display device that it's attached to.
The computer sends a descriptor about the display to the HID device ( the mouse ) the mouse then uses the information about the logical size of the screen to co-ordinate the movements.
For example, to move with Mouse.move(100,100,0); you are not actually moving by 100 pixels, but by 100/(127-((-127)).
The only option is can suggest is to STOP the mouse and Restart it again - this will be easier to restart calculations again.
Heres my Logic Function to convert Percentage to appropriate values for Mouse.move();
int percentToLogic(int percent) { return percent*254/100; }


how do i connect my Arduino Nano to my Linux Laptop update:
I uninstalled the portable package of Arduino IDE, completely, and installed the IDE using sudo apt install arduino. yes, I verified that my Nano was plugged in, the status on the bottom right says Arduino Nano w/ ATmega328 on COM1, but sadly the IDE won't explain to me why the Tools > Serial Port section is still unavailable.

Also, the online version doesn't recognize the board even though it's plugged in and configured in the settings to look for a "Nano". I also used a reliable USB Hub I use for my drawing tablet, because that was one of the remedies to troubleshoot the lack of connection, and because the Hub seems to do a lot of good things around here.

end of update

I received an Arduino Nano as a gift a couple months ago and had to place it on a shelf as a mere dust collector, because it was not as easy as I thought it would be to get it working.
I plugged the Nano into my computer with a cable, and attempted to load an example "blink" program and it gives errors saying "no device connected" in the errors.

It does light up and flash, so I know it is receiving power, so how do I specify where the Nano is?
I am familiar with the /dev category and how to use code in Linux, but I don't know how to communicate with the Arduino, as in, know which block device the Nano is in /dev

now that Thomas has brought to my attention the "port" setting in the drop down menus, I just realized that the port is greyed out. that could be a good detail in troubleshooting this issue.

In the Arduino IDE, the mcu will show up in Tools > Port.
Your Arduino Nano will probably be visible at /dev/ttyUSB0 or /dev/ttyUSB1 following whatever is already plugged on USB. Make sure to select it.

Select Nano in Tools > Board.

Last step is  Verify/Compile your code (^R), then Upload (^U).

This link sounds to be a good read to start.


How can I drive this LCD TFT with an Arduino? As I understand it, the Arduino comes with a TFT library which uses SPI to drive LCD TFTs. I recently bought a TFT labelled "HY-32.TFT" on the front and "HY-TFT320_262k heyaodz111211" on the back.

It uses an XPT2046 touch screen controller, but I'm more interested in just getting something on the screen currently.

To use the Arduino library, I need to connect pins:

SCLK
MOSI
CS
DC
RESET

But I can't see these apart from some similarly named ones associated with TP (touchpad?) and SD (sd card), as the photo shows:

Is it possible to drive this with my Arduino? If so, how?

UPDATE: It looks like the datasheet for the controller and the board can be downloaded from 3.0" 3" TFT LCD Module Display + Touch Panel + PCB adapter.

From what I'm seeing, the touch screen and card reader use SPI but the LCD uses a bunch of Digital I/O lines. The link in Gerben's comment includes a library for the LCD that might be what you're looking for. I hope you're using a ATMega board as it doesn't look like an Uno or similar board will have enough I/O for the LCD.


Using SoftwareSerial library with EnableInterrupt I'm working on a project that involves both serial communication and GSM transmission.
I'm using the SoftwareSerial library for RS232 communication, and GSM (SMS) transmission:

TX and RX for RS232 : Arduino Uno D3 and D4 pins
TX and RX for GSM module : Arduino Uno D7 and D8 pins

The project requires also the use of the EnableInterrupt library to enable interrupt in Arduino's analog pins, meaning that I DON'T USE EnableInterrupt for all of the Arduino's digital pins including D3, D4, D7 and D8.

However when running the program that includes the two libraries, this long error message shows up :

libraries\SoftwareSerial\SoftwareSerial.cpp.o (symbol from plugin): In function `SoftwareSerial::read()':

(.text+0x0): multiple definition of `__vector_3'

sketch\sketch_jun14a.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\SoftwareSerial\SoftwareSerial.cpp.o (symbol from plugin): In function `SoftwareSerial::read()':

(.text+0x0): multiple definition of `__vector_5'

sketch\sketch_jun14a.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\SoftwareSerial\SoftwareSerial.cpp.o (symbol from plugin): In function `SoftwareSerial::read()':

(.text+0x0): multiple definition of `__vector_4'

sketch\sketch_jun14a.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Erreur de compilation pour la carte Arduino/Genuino Uno

Clearly, there is a conflict between the two libraries, Is there any solution to remove this conflict and run the two libraries together ?

Thanks in advance !

SoftwareSerial uses all PinChange interrupts.
EnableInterrupts uses all PinChange interrupts.

You can see the conflict.

All you can do is to modify both libraries to remove support for the interrupts you don't need it to support - that way you share out the responsibility for handling the different interrupts between the two libraries.


Problems with Windows 8.1 install of Arduino IDE I have replaced my Arduino, thinking it would solve the problem, but I still get it. Whenever I try to upload code, I get the error messages programmer is not responding and not in sync. Then I heard Arduino had drivers required. But my Windows 8.1 didn't recognize Arduino Uno. It was put in the other devices area as an unknown device in the device manager. The update driver button is greyed out. I get the message:

  The drivers for this device are not installed (code 28). There are no
  compatible drivers for this device. To find a driver for this device,
  click update driver.

That's the greyed out button… When I look at driver details, it says 'No driver files are required or have been loaded for this device.' For the not in sync/programmer not responding error, I've tried restarting the board before uploading, restarting whilst uploading, you say it, I've done it. How can I fix this so I can finally follow my dream to be an engineer/programmer?

Getting started with a new toolchain can be quite a challenge…

I'm not a Windows guy, but it looks like there are drivers that need to  be installed to get things working with the Arduino. I'm guessing that what is going on here is that Windows is looking locally for drivers and not finding them (or any indication that drivers are needed). I think the button was grayed out because it couldn't help – not because help wasn't needed.

Here are a few sources that I found by searching on:

  arduino driver windows 8.1

[SOLVED] Arduino drivers for Windows 8.1 64bit
Windows 8.1 (64bit) USB-serial driver for Arduino?
Installing the Arduino IDE – Windows 8.1 & 10
Install Arduino Drivers on Windows 8

While we're at it, it is worth mentioning that "out of sync" error message from avrdude are very common. A bit of searching here will find you some good resources on solving them as well – deal with the drivers first, then see if errors persist.


programming relays wit millis code Trainset info,

Turnout 1 = relay 1 - makes turnout track go left
          = relay 2 - makes turnout track go right
Turnout 2 = relay 3 - makes turnout track go left
          = relay 4 - makes turnout track go right
 Signal 1 = relay 5 - makes signal go green - train 1 starts driving
          = relay 6 - makes signal go red - train 1 stops for signal
 Signal 2 = relay 7 - makes signal go green - train 2 starts driving
          = relay 8 - makes signal go red - train 2 stops for signal

I have a arduino - uno and a 8 relay board.
I want to run a program (loop) for 1/2 hour / 1800 seconds.
Switching time should be 2 seconds (relay ON)

Can somebody help me with a millis code please.

Loop times should be:

relay 1 = (2),1250,(2),546 - total 1800 seconds
relay 2 = 620,(2),630,(2),546 - total 1800 seconds
relay 3 = 10,(2)1260,(2),526 - total 1800 seconds
relay 4 = 630,(2),640,(2),512 - total time 1800 seconds
relay 5 = 20,(2),1270,(2),505 - total time 1800 seconds
relay 6 = 600,(2),750,(2),446 - total time 1800 seconds
relay 7 = 640,(2),640,(2),516 - total time 1800 seconds
relay 8 = 1240,(2),450,(2),106 - total time 1800 seconds

Regards, Martinus van Walsum
xxxxxxxx@xxxxxxxx.com

This is functional. I would do more by making a function to be called with the time and state information. It would reduce the number of if statements. But this is simple to understand. I started with Blink without delay.

I did two relays. For the others, copy and paste, then change the relay numbers and times.

/*
  Blink without Delay
  http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/

const int On =  1;
const int Off =  0;

// constants won't change. Used here to set a pin number:
const int ledPin =  LED_BUILTIN;// the number of the LED pin
const int relay1 =  5;
const int relay2 =  6;

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

int    secondCount = 0;

// constants won't change:
const long interval = 1000;           // interval at which to blink (milliseconds)

#define onTime  2           //relay on time

#define relay1_on1 0
#define relay1_on2 (relay1_on1+onTime+1250)

#define relay2_on1 62
#define relay2_on2 (relay2_on1+onTime+630)

void setup() {
  // set the digital pin as output:
  digitalWrite(relay1, Off);
  digitalWrite(relay2, Off);
  pinMode(ledPin, OUTPUT);
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    //------------------------------
    // Relay 1
    if (secondCount == relay1_on1) {
      digitalWrite(relay1, On);
    }
    if (secondCount == (relay1_on1 + 2)) {
      digitalWrite(relay1, Off);
    }

    if (secondCount == relay1_on2) {
      digitalWrite(relay1, On);
    }
    if (secondCount == (relay1_on2 + 2)) {
      digitalWrite(relay1, Off);
    }

    //------------------------------
    // Relay 2
    if (secondCount == relay2_on1) {
      digitalWrite(relay2, On);
    }
    if (secondCount == (relay2_on1 + 2)) {
      digitalWrite(relay2, Off);
    }

    if (secondCount == relay2_on2) {
      digitalWrite(relay2, On);
    }
    if (secondCount == (relay2_on2 + 2)) {
      digitalWrite(relay2, Off);
    }

    //------------------------------
    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);

    secondCount++;
    if (secondCount == 180) {
      secondCount = 0;
    }
  }

}


Arduino sensors with various periods Right now I have DHT11, PIR sensor, relay, and a photocell on the same board. I am planning to upload the data to a web server. But I want both DHT11 and photocell to be uploaded hourly; PIR and relay by every 3s. Is it possible for a single Arduino to perform such thing?

Yes. Perfectly possible.

How accurate do you need the "hourly"? If you want any form of accuracy at all you will really want to use an RTC module to provide the real time.

Otherwise that, and the higher speed 3s updates, can be timed using the millis() function.  The BlinkWithoutDelay example in the IDE shows you the basic idea of working with timestamps to examine elapsed time.

Also there are simple libraries that could help you, such as SimpleTimer.


How can I add a LED to this build? I recreated this project from Fritzing in my circuits.io project then on the arduino itself, it all works fine just how I wanted it.

The concept behind it is:

You plug it in and the time is set to 00:00
You can adjust the time to the time now let's say 22:46
You can put in an alarm to wake up let's say an hour later at 23:46
The piezo beeps in stops, so not continious.

So now my question is, how can I add a led that flickers on the same rhythm as the piezo (when the alarm goes off)? Can someone help me in my circuits.io project?

An update/edit would be great! I'm relatively new to all of this.

Thanks a lot!

You need to add an LED and series resistor between a currently unused Arduino pin and ground.
In your setup() function, set that pin's i/o mode to OUTPUT.
Where the code turns the tone on, it should also make the LED pin HIGH.
Where the code turns the tone off, it should also make the LED pin LOW.


Powering 3 servo motors and Arduino Uno with one 9 V battery I wish to power an Arduino Uno board AND 3 servo motors using a single 9 V battery.
I have connected the positive terminal of the 9 V battery to the VIN pin. The negative terminal of the battery is connected to the GND pin immediately following. This, I believe, powers the Arduino Uno board.
Next, I have connected the power wires of all 3 servo motors to the 5 V pin on the Arduino board ( using jumper wires and a  breadboard). Similarly, all the servo ground wires have been connected to the second GND pin in the 'POWER' set of pins on the Arduino Uno board. And finally, the 3 signal wires from the servos have been connected to the three PWM pins on the 'DIGITAL' row, exactly pins 9, 10 and 11. THE SERVOS ARE NOT OPERATED SIMULTANEOUSLY, THEY ARE BEING OPERATED ONE-BY-ONE (but the load is still attached to each of them, a couple of grams is all).
Since the servo motors operate between 4.8 V - 6 V, and I don't have any spare AA batteries to approximate a 6 V battery, I thought this could solve the problem.My question is, does this pose any problems for the board or devices, does this draw a higher current? Will it damage the Arduino Uno board or the servo motors or any of the individual pins?  Please let me know soon, thank you very much.

I don't think anything should get damaged; the regulator is rated for 1A, and even beefy servos don't draw more than 200mA when moving against heavy load. The problem is that your battery won't last long. Even the heavy-duty Li primary 9V batteries are under 1000mAh, and the actual capacity is heavily dependent on the discharge rate.

Why can't you use a rechargeable Li-ion pack with an appropriate step-up or step-down converter?


Split a string as 2x16 for LCD How do I split a string into two based on it's length to display on a 2x16 LCD?

I have seen a function called length() to get the length of a string. But, any ideas how to split it in to 2x16 and trim the rest of the string?

Thanks

String::Substring does take a start and an end value. So you can do something like this:

String s1 = longtext.substring(0,15);
String s2 = longtext.substring(16,31);


How do I move more than 128 pixels when using Arduino Leonardo's Mouse.move? How do I move more than 128 pixels when using Arduino Leonardo's Mouse.move?
Is it possible to modify the header file or use a different library?
I used the MouseTo library, but it wasn't the move I wanted.
We want to move as fast as possible to the relative coordinates, not as one pixel.
I've searched almost every community, but I haven't.
Give them a hand.

The USB HID protocol for mouse is the limitation on sending more then a byte sized value for the mouse movement in one event.

You can't create a faster USB mouse. Repeat the call of the move() function. Of course you can use a function to call move() repeatedly to move to target destination.

void mouseMove(long x, long y) {
  long max = max(abs(x), abs(y));
  int count = (int) (max / 127);
  signed char stepX = x / (count + 1);
  signed char stepY = y / (count + 1);
  for (int i = 0; i < count; i++) {
    Mouse.move(stepX, stepY);
  }
  signed char resX = x - (stepX * count);
  signed char resY = y - (stepY * count);
  if (resX != 0 || resY != 0) {
    Mouse.move(resX, resY);
  }
}


Debugging a Nordic MCU (feather NRF52) using Segger J-Link I have an Afafruit NRF52 board with SD 132 and 5.1 dual fw bootloader.
I implemented RTT logging and controlling (input) and the code is compiled using arduinoBuilder with RTT and debug level 3.
The device uses to control DALI lights but sometimes it hangs, I can see that it does not responses to input and light level never changes.

I want to debug it, maybe getting a stacktrace to see where it hangs, hoping it's a software issue.

Any leads on how to do that ?
Tutorial maybe ?

I haven't tried this, but OpenOCD supports both the nRF52 and the JLink.  Something like (on Linux):

openocd -f /usr/share/openocd/scripts/interface/jlink.cfg -f /usr/share/openocd/scripts/target/nrf52.cfg

might start OpenOCD.

You can then connect with (nRF52 flavour of) gdb (arm-none-eabi-gdb).

You can find information about using gdb with OpenOCD here and here.


Having trouble with motor shield running off external power source I apologize if I don't immediately give important info, I'm very new to arduino's/circuity of any kind.  I'll try to include as much info as possible.

Some preface:
I'm currently working on a project that generates electricity using TEG's (Thermoelectric generator). The setup I currently have is able to output upwards of 9V. The motor I'm using is able to run when directly connected to the TEG wires, sp they produce enough electricity to work. Due to the nature of the project, a stopping mechanism is being used via a photoresistor and an LED. Essentially when the light signal picked up by the photoresistor is low  enough,  power is cut to the motor.

So up until recently, the motor and the Arduino board/motor shield (Arduino UNO, Arduino Motor Shield Rev3) were being run using a 9V battery. Everything worked correctly, the motor would start when needed and stop when needed. Once I switched to the TEG's the set up stopped working (motor stopped running). What is weird is that if I connect a voltmeter to channel 1 of the motor shield, I read 6V-7V (some voltage drop but not drastic) when the LED was on and 0 when the led was off. So everything seemed to still be working, but the motor itself just won't actually run. In fact, when the LED is on, it makes a very faint noise for a second but doesn't run.

The only thing I can think of is that the current being produced by the TEG's is only enough to power the motor when directly connected, but when wired indirectly through the board thus powering the board, it no longer has enough amperage.

I included the code I wrote for it, which worked fine with a 9V battery powering the motor/board.

const int sensorPin = A5;
const int ledPin = 5;
int lightLevel;

void setup(){
  Serial.begin(9600);
  pinMode(12,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(ledPin, OUTPUT);
}

void loop(){
  lightLevel = analogRead(sensorPin);
  lightLevel = constrain(lightLevel, 0, 800);
  Serial.println(lightLevel);

  if(lightLevel < 200){
    digitalWrite(9,LOW);
    digitalWrite(12,HIGH);
    analogWrite(3,255);
  }
  if(lightLevel > 200){
    digitalWrite(9,HIGH);
    analogWrite(3,0);}
}

Try a decoupling capacitor acorss your TEG : 100µF/35v (+ at the +).
This will avoid micro power drops...
Verify that y hardware driving motor works below 9V.


Options for powering a Futaba servo In one of my earlier questions it was determined for me that my Futaba Servo should not be powered directly from the 5v pin of my Arduino and should instead be powered by an alternative source. I was told the Servo requires a “high current 5 volt power supply” so I’m wondering what my best options are as my knowledge in servo control is quite limited. Is there some type of board that helps with this? Do I need a specific battery? If the servo needs a battery could it run off of the same battery as the arduino? Im trying to keep my design as compact as possible so multiple battery packs could pose complications.
The specific information can be found here.
Thanks for any help!

Based on the link to the specifications, this is a "high speed, high torque" servo. Unfortunately, none of the information includes the maximum or typical current draw, though there are warnings to higher gauge wire than usual and to avoid long leads and Y-splitters.

These are indications that your power supply should be "beefy", and by the class of servos this is in, I would guess you need a supply capable of supplying 5V at up to 3 amps.

The "harder" the servo has to work to move, the more current it will draw. This servo wants around 5V, but 4.8V is acceptable from a 2S (2 series) LiPo battery pack.

4.8V, however, is not quite enough for a 5V Arduino at 16MHz (the standard speed). As long as all the Ground wires are connected together, you could have one battery pack for the Arduino and a 4.8V pack for the servo.

All that said, there are only 2 primary specification points of a power source -- Output Voltage and Max current. You should try to MATCH voltage ratings of a power source to the device being powered, and ensure the device being powered DOES NOT EXCEED the current rating of the power source.


Using Analog Comparator on ATmega32u4 I am (currently) parsing a PPM analog signal using an Arduino Uno R3 using the analog comparator ASCR and analog hardware interrupts using AIN0 and AIN1. I am applying a specific negative comparison voltage using a linear voltage regulator on AIN0 and the signal on AIN1.

Code snippets:

setup

  ACSR  = B00011011;

outside other closures

ISR(ANALOG_COMP_vect) {
   CRCArduinoPPMChannels::INT0ISR();
}

I am trying to move this project to an Arduino (compatible) Pro Micro from SparkFun. The datasheet specifies AIN0 on ATmega32u4 pin 1 but do not see a reference to AIN1.

The datasheet outlines use of the analog comparator on page 289:

  AIN+ can be connected either to the AIN0 (PE6) pin, or to the internal
  Bandgap reference. AIN- can only be connected to the ADC multiplexer.

I have connected the signal to Arduino pin 7, the comparison voltage to Arduino pin 20 (analog 2) and set the following options of the ADMUX register:

ADMUX = B11000101;

The interrupts trigger but the comparator voltage (AIN-) is not being observed. Any help would be appreciated.

AIN- won't be connected to the ADC mux unless ACME is set and ADEN is cleared. Don't forget to do so.


Connect ethernet cable wires directly to pins Is it possible to uncrimp a RJ45 plug and connect the wires directly to the Arduino pins? I guess I'd have to decrypt the ethernet signal then on my Arduino which might not have enough processing power at command for such a task.

I don't want to do it with an Ethernet shield, so please don't link any in the answers.

I am by no means an expert on this, this answer is ~20 minutes of me googling things, but I would say that in theory it is probably possible to do this with an arduino, at least at the lower transfer rates anyway, and certainly from a "will it kersplode my board" point of view - probably not since ethernet runs at +/- 2v (ish) and ~10mA (ish). However:

The ethernet protocol is exceedingly complex, with many layers needed to actually communicate with anything useful, all of which you would have to implement from scratch (there won't be a library to just drop in) and I'm not completely convinced that an entirely software-based implementation of the stack would fit on the arduino (but I could definitely be wrong there - and actually, on further thought, this probably is wrong, but I reckon I couldn't write it so it fit, but I'm a reasonably average human being).

Arduino is all about hacking and re-inventing wheels just for the fun of it but I am absolutely certain that there is no fun to be had re-engineering Ethernet and TCP/IP and all of the stuff in betweeen from scratch (obviously my opinion, I enjoy all sorts of things others don't, so YMMV).

My suggestion would be - if you don't like ethernet shields, look into getting a 'raw' ethernet controller chip (like the one soldered onto an ethernet shield) and build it directly into whatever device you're trying to make first, that'll give you plenty of exposure to how ethernet works at that level, then you can decide if you're still up for re-inventing the brain that invented the wheel. Good luck!


How to load Atmega328p 8mhz board using board manager I need to load the Atmega328p 8kHz board definition using the board manager and can not find a way.  Any help will be appreciated.

Assuming that you have a 3.3V Atmega328P and are using an external 8MHz occilator:

In the Arduino IDE click on Tools.
Scroll down until you see an option starting with the word Board:
Select the option called Arduino Pro or Pro Mini

Click the Tools menu once again.
This time select the option starting with Processor:
Select the Atmega328P (3.3V, 8MHz)
Done!

Alternatively you can edit the boards.txt file located somewhere similar to C:\Program Files (x86)\Arduino\hardware\arduino\avr
Fuse bits can be calculated using one of these online tools:

http://www.engbedded.com/fusecalc/
http://eleccelerator.com/fusecalc/


What type of relay will handle a 51 amp 10 hp motor and a 75 amp 15 hp motor? I'm using an arduino uno and gprs gsm shield with Numato relay.

What type of relay will handle a 51 amp 10 hp motor and a 75 amp 15 hp motor?

A very very very large one, by normal standards :-).
That is a substantial requirement and  needs a relay specialist to check what you are doing.

What voltage are you using and is it AC or DC.
1 HP = 746 Watts, so 10 HP = 7460 Watts
V = W/I = 7460/ 51A = 146V.
Which may mean you have a 110 VAC system with an allowance for starting, or ...?

That spec will allow a reputable relay supplier to ask you whatever other questions are necessary to fine tune what they offer. Things like:

AC or DC makes a HUGE difference.
Voltage makes a difference.
Whether you have any sort of on-line starter or if this IS the online starter makes a difference.
Whether the motors start loaded or are run up to speed and then loaded can make a large difference.
N/C or N/O operation makes some difference (which may not be intuitively obvious)
Other ... the specialist will ask questions.

What is the application?

Serious question: What sort of answer did you expect?.


SdFat: Why does the first write to the file take so long? I have tested this problem on 6 micro-SDHC cards of 3 different types. 3 are 32-GB Sandisk, 2 are 16-GB Kingston, and 1 is 16-GB Samsung. These cards are used in data loggers and typically contain hundreds or thousands of 5-MB text files whose names are formatted like FILE1234.TXT.

The problem is that when a logger containing such a card (containing data) is started, the first write takes a long time--from 7 to 30 seconds. Opening the file (the smallest available filename) doesn't take too long. Subsequent writes don't take long. Just the first write.

Now, the plot thickens: this delay can be eliminated by first opening FILE0000.TXT and immediately closing it. Further, once this is done, that disk is never affected by this delay again. This has happened with each of the disks.

Here is some minimal code demonstrating the issue:

#include <SdFat.h>
SdFat sd;
SdFile file;

void setup(){
  Serial.begin(57600);
  sd.begin();
  int m = millis(); // just to time everything

  // critical line that prevents delays
  file.open("FILE0000.TXT", O_WRITE | O_TRUNC | O_CREAT); file.close();

  // file we actually want to write to
  file.open("FILE6005.TXT", O_WRITE | O_TRUNC | O_CREAT);
  Serial.println(millis()-m); // print how long it took to open

  file.println(F("test"));
  Serial.println(millis()-m); // print how long it took to write
  file.close();
}
void loop(){
}

When the "critical line" in the code is commented out, I get a big delay in the first write to the file. When it's uncommented, there's no delay, and I never get a delay on that disk again even with the line commented. I saw this on all six disks.

One further bit of mystery: at first, this did not work on one of the cards. I checked and found that this card alone had a hidden ".Trash-1000" directory. I removed that directory and tried again, and this fix did work that time.

Does anyone have any idea what's going on here?

Most file systems exhibit poor performance if you store many files in one directory. 'Normal' desktop computers are perhaps so fast, that you don't notice the performance impact, but accessing the file system from a relatively slow micro-controller, which also have limited means of caching the file system data structures in RAM, you may have to consider for this and either write a smaller number of files or build a tree of directories, so that you only have a limited number of files in each directory.


What is the best data type to be used through i2C i'm trying to send multiple commands to multiple slaves controlling motors. Slave Controller(Arduino Nano) will receive the command, and returns the current position of the motors to the Master(Arduino Mega).

What data type would be best to use in this scenario. I am considering, string or byte data type.

I2C works with fixed size byte arrays.

Single bytes for commands should be sufficient. For positions you might need int16_t or even bigger numbers. Unsigned positions relative to (above) zero might make things easier, eventually (?)

As you have the same architecture on both sides, mapping of byte arrays to bigger numbers via union will work well.


Arduino is incorrectly reading serial input from C# program I am trying to create a program to operate my arduino based LED controller. I'm pretty sure that my C# program is outputting to serial port correctly as I double checked the output in Debug.WriteLine(). The program is supposed to send information to the arduino in the following format (newlines included):

mode
number of colors
blend speed
beats until color change
Red   <---
Green <---
Blue  <---
Brightness <---

the last 4 are the only ones that matter for now as I am trying to get the LED's to show up one solid color first before worrying about other modes or patterns. The debug writeline loop output of my last test looks like this

1
1
0
1
209
255
255
219

This should be translating to the relevant arduino variables the same way but instead, I only get white light that seems to randomly brighten or darken when I mess with the color/brightness sliders

My code for the arduino is below. I am very new to this so it's probably not even close to right. getData() at the bottom is the function that most likely is the culprit, but I'll put the rest in just in case:

#include <SPI.h>
#include <Adafruit_DotStar.h>

#define NUMPIXELS 60

Adafruit_DotStar strip = Adafruit_DotStar(NUMPIXELS, DOTSTAR_BRG);

// Variables
int mode;
int numColors;
int fadeSpeed;
int BBCC;
int R;
int G;
int B;
int Bright;
String buff;

void setup() {
  strip.begin();
  strip.show();
  //Serial.begin(9600);
}

void loop() {
  getData();

  if (mode == 1)
  {
    //strip.setPixelColor(0, R, G, B);
    strip.setBrightness(Bright);
    strip.show();
  }
}

void getData()
{
 // if (Serial.available() > 0)
 // {
    buff = Serial.read();
    int result = buff.toInt();
   mode = result;
   if (mode != -1)
   {
    buff = Serial.read();
    int result = buff.toInt();
    numColors = result;
    buff = Serial.read();
    result = buff.toInt();
    fadeSpeed = result;
    buff = Serial.read();
    result = buff.toInt();
    BBCC = result;
    buff = Serial.read();
    result = buff.toInt();
    R = result;
    buff = Serial.read();
    result = buff.toInt();
    G = result;
    buff = Serial.read();
    result = buff.toInt();
    B = result;
    buff = Serial.read();
    result = buff.toInt();
    Bright = result;//Serial.read();
    strip.setPixelColor(0, R, 0, 0);
    //strip.setBrightness(Bright);
    strip.show();
   }
   else
   {
    strip.setPixelColor(0, R, 0, 0);
    //strip.setBrightness(Bright);
    strip.show();
   }
//  }
}

Your Serial receive code is not correct in some ways:

You should only read from Serial, if there is really something to read. For the first read, that is not the problem, since you checked against the return value being -1 (which is the return code for "there is no new data in the buffer). But after that, you read without ever checking, if there is something to read. You need to understand, that the data is really send serially. The bytes come in one after another and there is no concept as messages on the Serial interface (which is actually called UART in non-Arduino environments). More over, there might be small pauses somewhere in the transmission, since you cannot foresee, when exactly the PC will send the data (the PC has a bunch of other tasks to do, too). So it might be, that you have received one byte, which will lead you into the if statement, but the rest of the data will arrive later. All data is then read as -1, since there is no data in the buffer.

You have to check, if there is actually data to read, before reading. This can be done with Serial.available(). It will return the number of new data bytes in the buffer. For example, if you want to read 8 bytes, you should wait, until at least 8 bytes are inside the buffer by using if(Serial.available >= 8).
You are sending the data from the PC as ASCII encoded text. That means, that every number above 9 consists of multiple data bytes. The 4 values, that you are interested in, are all over 200, which means, that you need to read 3 bytes to get them. But you only call Serial.read() once for every value. That will give you the first digit, which is a 2 for all values in the shown data. More over, since you only read 1 byte, where there is the whole number (which may be multiple bytes) plus 1 or 2 bytes for the new line (depending on the chosen line ending \n or "\n\r"), The whole reading gets misaligned to the data structure. Now the read data (if there is any) is also dependent on how much data was send for the values before.

Keep in mind, that with ASCII encoded text, you may need multiple Serial.read() calls to actually read a full number. I will describe the way to go here in the next point.
As I already mentioned above, there is no message protocol on the Serial interface. Lost data would lead to misalignment and thus garbled data. But you can impose an own protocol onto the Serial stream of data. It is a good practice, to first receive a full message (maybe with multiple data values inside it) and then process it. For that I would suggest a new data structure

mode|number of colors|blend speed|beats until color change|Red|Green|Blue|Brightness\n

The new line is here realized only with a newline character (\n). The values are separated with a vertical dash. You should put an if(Serial.available()>0) into your loop function. Then inside that if statement, you read one character and add it to a buffer. If you read the \n character, you start to process the buffer. You can then convert one value after another from the buffer and save them into variables. After that, you clear the buffer. You can see this style in the SerialEvent example, that comes with the Arduino IDE. You should also read Majenko's blog article about reading the Serial interface on the Arduino.

That said, you should be cautious with using String object on the Arduino. Sure, Strings are convenient, but they dynamically allocate the needed memory during the runtime. On microcontrollers, which normally have very limited RAM memory, that can lead to heap fragmentation (heap is the memory area for dynamic memory allocation). When using String objects, the underlying buffer get's often recreated. As buffers get allocated and deleted later, that can lead to small memory areas, which are unused, but to small to actually be used by the buffer. You can fill up your RAM very fast with that.

It is better to not use String, but directly a char array with a fixed length. Majenko also wrote an article about the String problem: The Evils of Arduino Strings


Configuring IO18, IO19 for I2C connectivity on Intel Edison Kit for Arduino Intel Edison Kit for Arduino Hardware Guide instructs:

echo 28 > /sys/class/gpio/export
echo 27 > /sys/class/gpio/export
echo 204 > /sys/class/gpio/export
echo 205 > /sys/class/gpio/export
echo 236 > /sys/class/gpio/export
echo 237 > /sys/class/gpio/export
echo 14 > /sys/class/gpio/export
echo 165 > /sys/class/gpio/export
echo 212 > /sys/class/gpio/export
echo 213 > /sys/class/gpio/export
echo 214 > /sys/class/gpio/export
echo low > /sys/class/gpio/gpio214/direction
echo high > /sys/class/gpio/gpio204/direction
echo high > /sys/class/gpio/gpio205/direction
echo in > /sys/class/gpio/gpio14/direction
echo in > /sys/class/gpio/gpio165/direction
echo low > /sys/class/gpio/gpio236/direction
echo low > /sys/class/gpio/gpio237/direction
echo in > /sys/class/gpio/gpio212/direction
echo in > /sys/class/gpio/gpio213/direction
echo mode1 > /sys/kernel/debug/gpio_debug/gpio28/current_pinmux
echo mode1 > /sys/kernel/debug/gpio_debug/gpio27/current_pinmux
echo high > /sys/class/gpio/gpio214/direction

However line 3 already gives an error:

echo: write error: No such device

Any suggestions on how to enable I2C?

It was a strange problem which we were not able to resolve in an acceptable manner after all.

The problem disappeared after we re-flashed the device.


Intterupts For Arduino I am making a moving robot that will be autonomous in many respects. However if something goes wrong I want to be able to use a remote to push a button and it stop in its tracks no matter what function its in.  My understanding is that interrupts can do that. The official site I did not find to be helpful. Any ideas? Or if the scheduler library would be of use.

An interrupt can not always stop the code, although that is almost always the case. Certainly having an interrupt based kill switch would be better than a "regular code" polled one, which would still be better than nothing. If possible I would feel safest with a cut-power-to-the-whole-thing style safety switch.

Many functions that have sensitive timing constrains disable interrupts while they are active. It is rare for any of these to take a noticable amount of time, but it is possible that a bug in an interrupt dissabled function or another interrupt function could cause it to block and in that case your stop switch wouldn't work. rare, but possible.

I suppose you could turn on the chip watchdog timer, have a regular timer based interrupt reset the watchdog timer at a certain interval, and have your interrupt safety switch enabled. Then if interrupts ever stopped firing for too long the chip would reset itself. Checkout AVR132: Using the Enhanced Watchdog Timer. I've never used the watchdog myself, but it exists for a reason.

I don't have enough experience with a scheduler system to know if they would be helpful.


How to count the number of button presses then play a sequence? When I press the button once, sequence s1() plays.
When I press the button twice, sequence s2() plays.
When I press the button thrice, sequence s3() plays.
When I press the button 4 times, sequence s4() plays.

const int buttonPin = 10;
int buttonState = 0;

void setup(){
  Serial.begin(9600);
  //initialize pin 2 - 9 as output
  for(int i=2;i<=9;i++){
    pinMode(i,OUTPUT);
  }
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    s1();
    s2();
    s3();
    s4();
  }
}

void s1() {
  int i = 2 ;
  for(int z=0;z<=1;z++) {
    for(int x=i;x<=9;x++) {
      digitalWrite(i,HIGH);
      digitalWrite(x-1,LOW);
      delay(500);
      i = i + 1;
    }
    i = 2;
    if(i = 2) {
      digitalWrite(9,LOW);
    }
  }
}

void s2(){
  int y = 9;
  for(int i=0;i<=1;i++) {
    for(int x=2;x<=5;x++) {
      if(y>=1) {
        digitalWrite(x,HIGH);
        digitalWrite(y,HIGH);
        delay(500);
        y = y - 1;
      }
    }
    off();
    y = 9;
    delay(500);
  }
}

void s3() {
  for(int i=0;i<=2;i++) {
    for(int z=2; z<=9;z++) {
      if(z % 2 == 0) {
        digitalWrite(z,HIGH);
      }
    }
    delay(500);
    for(int z=2; z<=9;z++) {
      if(z % 2 == 0) {
        digitalWrite(z,LOW);
      }
    }
    delay(500);
    for(int z=2; z<=9;z++) {
      if(z % 2 != 0) {
        digitalWrite(z,HIGH);
      }
    }
    delay(500);
    for(int z=2; z<=9;z++) {
      if(z % 2 != 0) {
        digitalWrite(z,LOW);
      }
    }
    delay(500);
  }
}

void s4() {
  for(int i=0;i<=2;i++) {
    for(int x=2;x<=9;x++) {
      digitalWrite(x,HIGH);
      delay(500);
    }
    off();
    delay(500);
  }
}

void off() {
  for(int i=2;i<=9;i++) {
    digitalWrite(i,LOW);
  }
}

That's not that complex, please have a look at the following code: not the most elegant solution ever, but should be working (I didn't compile it as I'm currently on launch break in the office)

#define LONGEST_PAUSE 1000
unsigned long lastClick;
unsigned int counter;

void loop() {
  if (digitalRead(buttonPin) == HIGH) {
    // button is pressed
    while(digitalRead(buttonPin) == HIGH)) {
      delay(1); // wait until button released
    }
    lastClick = millis();
    counter++;
  }
  if (counter > 0 && (millis() - lastClick) >= LONGEST_PAUSE) { // 1s passed since last click: let's play!
    switch(counter) {
      case 1:
        s1(); break;
      case 2:
        s2(); break;
      case 3:
        s3(); break;
      case 4:
        s4(); break;
      default:
        // what if I keep clicking?!?
    }
    counter = 0; // reset the counter
  }
}


Is there any way to separate this short code into its own function? (webserver, trying to use client.print outside of main loop) I have an arduino webserver that uses the following code:

client.println(F("HTTP/1.1 200 OK"));
client.println(F("Content-Type: text/html"));
client.println();
client.println(F(""));
...
if (fan1Toggle == 0)
    client.print(F("Fan1&#8226;On
"));
else
    client.print(F("Fan1&#8226;Off
"));

if (fan2Toggle == 0)
    client.print(F("Fan2&#8226;On
"));
else
    client.print(F("Fan2&#8226;Off
"));
...

The page is pretty long, allowing the user to toggle over a dozen different switches. Some of the code checks to see the state of a certain switch, and then displays a green or red bullet ("&#8226", like •) on the page if the switch is on or off.

Since the code for the colored bullet is repeating, I wanted to make a function for it. Then I would just call (for example) "displayBullet(fan1Toggle);", and it would determine if fan1 was on or off, and display the correct color depending on the state.

I tried to create the following function:

void displayBullet(int toggle) {
if (toggle == 0)     //switch is off, so display red bullet
    client.print(F("&#8226;"));
else    //switch is on, so display green bullet
    client.print(F("&#8226;"));
}

But then I got an error saying that "'client' is not declared in this scope".

Is there any way to work around that error, so that I can get the displayBullet() function I want? Or is this something that can't be shortened like this, because the "client" function has to be inside the main loop?

Thanks!

You can pass client to the function by reference, like this:

void displayBullet(EthernetClient & client, int toggle)
  {
  if (toggle == 0)     //switch is off, so display red bullet
    client.print(F("&#8226;"));
  else    //switch is on, so display green bullet
    client.print(F("&#8226;"));
  }

Now it knows about client. Make sure you pass client when you call it:

displayBullet(client, 1);


Measure plant pot amperage production My son is working on a school project, He wants to measure microbiological interaction with soil and plant.
In his protocol, he has to measure the amperage of the soil. I would like to help him with some automation and Arduino.
But I can't find a module that does this work for him.
Have you got some resources or maybe a small and easy PCB to achieve this?
Firsts measurements tend to reveal that microbiological product small ampere, near the micro/nano ampere.
Edit : I think I don't explain correctly what we are trying to achieve :
The plant rejects sugar through its roots, then the bacteria eat the sugars and these bacteria release electrons in the medium, and it is this phenomenon that we want to measure.
It is the bacteria that produce the electrons because a whole test protocol has been put in place to ensure the phenomenon.
So we want to monitor this electron production and then make some and correlations analyze to see if it's benefit to the plant or not.

I think he wants to measure the resistance of the soil. I saw many projects (I was a science fair judge) that did it with an ohm meter or variation thereof. They would have several samples of soil and add nutrients to it, generally with water. Salt was the best conductor. Similar tests were performed using Ph as the measurement. An Ohm meter passes a current through the DUT (Device Under Test) and measures the voltage drop to determine resistance, maybe that is where amperage came from. I am guessing this is maybe about a seventh grade project. More information always helps.


Detect a non-human moving object I would like to design a system in which I am able to make a light flash when a motion sensor detects a movement of a non human object such as a car.

(The goal here being that when a car is moving behind me in my blind spot around the corner of a wall in my parking spot I don't back into it.)

I have looked into a few tutorials using arduinos to detect this motion but so far I have only read about the PIR (which only detects humans and animals).

http://www.instructables.com/id/DIY-Arduino-Motion-Sensor-Lighting-Control/?ALLSTEPS

What sensor would be best for this situation or do I need to rethink my system?

(I have no intention of harming anyone or anything :) )

If your car is moving at the time, then relative to your car everything is moving.

Automotive companies have spent billions of dollars working on this problem.  There is no "sensor" that can differentiate one moving object from a background that is also moving.

All existing automotive systems that perform this task use cameras and computers, with software such as OpenCV.  This is not something that any Arduino could even come close to doing.

The closest you could get is "is there something in this area that is within a certain distance of me" which you may be able to do with an ultrasound "Ping" sensor.  It won't differentiate between a moving car or a bollard or a child or just the wall you are reversing towards.


analogRead values all over the place, while measuring light I'm trying to detect light using an led that's already attached to the circuit. I have a flashlight shining on the led.

Minimal sketch:

while( true )
{
    int photoValue = 0;
    analogReference(INTERNAL);
    photoValue = analogRead(A5);

    Serial.println(photoValue);

    delay(300);

}

While I have my multimeter attached, it reads a pretty constant value around 5mV. The serial output however swings around, as seen in this sample output:

0
0
4
4
0
16
15
22
21
25
20
36
40
34
36
24
5
0
3
6
0
0
0
0

That would translate to values between 0 and 43mV.

When I disconnect the multimeter only get 1023 printed.

I don't get how the values from the ADC and the multimeter, totally don't match.

The problem you are facing is that the output of the LED is too high impedance for the ADC to work reliably.

Basically the LEDs can't produce enough current to charge the S&H capacitor properly, and on top of that the LED doesn't act as a resistive load when not forward biased, so the input is basically floating and picking up noise.

The best cure is to add a voltage-follower buffer with incredibly high input impedance in front of the ADC input.

By high impedance I mean something measured in the 10s to 100s of TΩ. Something like the OPA355.


How to upload and play music file directly to ATMega328 arduino nano I'm wanting to upload a v short piece of music, to an arduino nano, and then play it repeatedly.

The file length only needs to be 10ms, how do I do this?  I'm unsure what format to put it in, where to put it in the code and also the size limits (Is it 2kb (RAM size) or 32kb (EEPROM) size that will decide how big a file I can put in?

I don't know how/where to put the code and how to get it to play.  I found lots of information on running it off SD cards or other external memory, but these aren't an option at the moment as I am limited to what I currently have (currently - an arduino nano, a load of resistors, diodes and that's about it) I'm just wiring the speaker directly between pin4 and ground but could do more wiring if that's required.

I'm quite happy to reduce the sample rate of the file down to get it small enough to fit the 2kb or 32kb size - but I have no idea what to to/where to paste the code/even where to get the code from a .wav or .mp3 or whatever filetype.

Thanks very much

The website below will give you the full information on how to do it. You will need a speaker connected to a PWM pin (I think that pin 3 on the Nano should be one of these kind of pins).

You can download the extension for the IDE to play your music and a program, on which you will convert the .mp3 files to a numeric format, which you will then paste in your program.

http://highlowtech.org/?p=1963


Open WiFi Configuration Automatically Is it possible to have an Arduino Uno + WiFi 101 recognize when the USB cable has been connected and prompt a user to enter a network name and password?

Can this be stored on the Arduino itself or does it need to be something run locally on the user's PC?

To render a UI, you need a PC program. It would handle presenting an interface as well as communicating the user's input to the Arduino over UART. I would recommend writing your own program as it would give you a lot of freedom in the UI design. Processing and Python are good options. To avoid using the IDE, you'll need a USB-TTL adapter cable. If you use the default USB connection, you need the drivers which only ship with the installer AFAIK. To detect the COM port, you can either have the user check the Device Manager or make your program auto-detect it, though this isnt very reliable. This link shows some Python code on detecting the Arduino's port or at least, displaying a list of open ports and allowing the user to choose. You can set the baud rate and other stuff permanently in your code; the COM port is the only variable. Also all handshaking b/w the Arduino and PC can be done without the knowledge of the user.

That said, there are already existing programs (for most common OSes) that can provide minimal functionality. If you dont need a fancy GUI, then putty (on Windows) can serve to read input from a user and pass it on to the listening Arduino. You can use putty's default baud rate (9600) in your Arduino sketch so that the user doesnt have to set this. Again, the COM port must be known. Device Manager is the only real option.

With this second approach, you could make a user enter some string (or even a char) in putty to prompt the Arduino to ask for the SSID and password. Once the Arduino is powered, it does nothing but wait for that input string and once it receives it, it sends something like: Enter SSID: , the user complies (and presses the Return key to terminate) and this is repeated for the password. The Arduino sketch would look like this:

#define MAX_LEN 20  //max length of name or password

char PROMPT[] = "ready\r"  //the initial string input from a user
char SSID[MAX_LEN];  // buffers for the ssid and pwd
char PWD[MAX_LEN];

init_done = 0;  // this var is set when an ssid and pwd have been received

void setup(){
  Serial.begin(9600);
  //anything else
}

void loop(){
  if (!init_done)
    continue;
  //  your other code
}

void get_data(){
  Serial.print("Enter Network SSID: \r\n");
  while (Serial.available() == 0);  // wait for input

  // no timeouts used here; wait till user presses return key
  int i = 0;
  char c;
  while (i < MAX_LEN - 1){  // read chars till the buffer is almost full
    c = Serial.read();
    if (c == '\r') // means end of input
      break;
    SSID[i++] = c;
    while (Serial.available() == 0);  // wait for next char
  }
  SSID[i] = 0;  // null terminate
  while (Serial.read() != -1);  // flush serial buffer

  Serial.print("Enter password: \r\n");  //same as before
  while (Serial.available() == 0);

  i = 0;
  while (i < MAX_LEN - 1){
    c = Serial.read();
    if (c == '\r') // end of input
      break;
    PWD[i++] = c;
    while (Serial.available());
  }
  PWD[i] = 0;
  while (Serial.read() != -1);

  //Serial.print("Done.");
  init_done = 1;
}

void serialEvent(){
  if (!init_done){
    while (Serial.peek() != PROMPT[0]) // read off any garbage
      Serial.read();
    int i = 0;
    while (1){
      if (Serial.peek() == PROMPT[i++]) // compare received chars to PROMPT
        Serial.read();
      else
        return

      if (i == sizeof(PROMPT)){ // read enough chars
        while (Serial.read() != -1);  // flush the buffer
        get_data();  // get ssid and so on
      }
    }
  }


How do I create a 9 bit number based on values from 9 digital inputs? I have 9 pins that are inputs from 9 IR LEDs. I want to combine all their results into one 9 bit number.

example:
pin1 = high,
pin2 = high,
pin3 = high,
pin4 = low,
pin5 = high,
pin6 = low,
pin7 = low,
pin8 = high,
pin9 = low

9 bit number = 111010010

In your code you would use a 16 bit unsigned integer as your variable. As there is no such thing as a 9 bit type.

If the pins correspond to different ports on your micro, you basically do this:

Read the pin value from the port register, and bit shift to the right bit position then OR with the variable.

Say you had 8 of the LEDS on PORTB (pin 0 - 7 )and the 9th on PORTC (pin 2)

unsigned int ir_inputs = 0

ir_inputs = PORTB; //just reads the register directly
ir_inputs = ir_inputs|((PORTC & 0x04)<<6); //reads the bit on pin 2 then shifts it 6 places to bit 8 (or the 9th bit remember bits always start at 0) and does not affect the other bits

something like that

actually you could put it into a function

unsigned int getIRinputs(void){
    return (unsigned int)PORTB|((PORTC & 0x04)<<6);
}

Easy done

Even if you had the inputs on 9 separate ports the principle is the same.
Read, Shift, OR


Graphical programing language for Arduino I am looking for a graphical programming language for a project of mine, where I am using an Arduino.

It HAS to meet the following conditions:

It supports uploaing sketches to ATmega328 (Arduino Uno/Nano)
New functions can be defined inside the programming enviroment (I am trying to use a motor connected to an H-bridge with a single command block)
The program can run on Windows 7
Libraries can be used inside the code
C++ can also be used to write the code inside the same program
Sketches can be uploaded via Bluetooth 4.0

It would be nice if it met the following condition:

The programming enviroment is easy to use
The graphical programming language is somewhat similar to Scratch
The program can be understood by 10-14 year olds with no programming experience

The most full featured Scratch-like environment for Arduino, to my knowledge that is close to your listed criteria is http://www.mblock.cc/

It's currently in beta development for enabling bluetooth uploads and supports a range of "extension" plugins.  I believe you can also add functionality by writing your own extensions if you have sufficient programming knowledge.

The software has more features if you use their mblock hardware, while offering a reduced set of commands for other boards such as the Uno.

I'm sure you can add library's to your code but at the expense of the scratch-like interface.  A children's visual design tool being able to provide graphical API to libraries written by an open source community is quite a coding challenge.  You can get a feel for this by trying to use any reverse engineering C++ to UML diagram tools.

I recommend perhaps using one of these scratch tools to build simple firmware as a learning tool with the idea of progressing to an actual programming language soon after.

In any case I hope you find what you're looking for among these options for your project.

http://www.mblock.cc/
http://s4a.cat/
http://blog.minibloq.org/p/documentation.html
http://blog.ardublock.com/engetting-started-ardublockzhardublock/
https://www.visuino.com/


High range Obstacle detection system I am making a high range and fast Obstacle detection system ,
HC-04 is slow for that, other sensor don't have the range and Lidar is too costly.

Any idea how to make a long range(more than 10m) high speed Obstacle detection system

You can Use PIR Sensor which is Cost Effective and covers upto 10 Meters


Bluetooth Low Energy dropping data at 115200 baud? I'm transmitting serial data from a sensor on my Arduino simultaneously to my laptop via USB and to a terminal app on my phone via a genuine HM-10 BLE module (onboard a Linksprite BLE Shield).

At 9600 baud, the BLE module was transmitting all of my data to the phone's terminal app without issue. I just figured out how to increase the HM-10 module's baud rate to 115200 (for reference, by sending it an AT+BAUD4 command at 9600 baud from the Arduino IDE console via USB, and then uploading a new sketch to the Arduino with both the USB serial and BLE serial baud rates set to 115200). The data is being received via USB serial flawlessly, but the data received by the terminal app on my phone via BLE appears to be missing chunks of data - and I have to try to connect to it 30+ times to get it to properly connect.

Is 115200 baud too fast to transmit data via BLE? Is there any way to make sure all of the data is properly sent via BLE without slowing the program down too much? 9600 baud is too slow for my application, unfortunately.

I should add that I am using an Arduino M0 pro and the BLE is connected via hardware serial (Serial1) and not SoftwareSerial as would need to be done on the Uno, if that makes a difference.

Well, I did some tests and was not able to reliably receive data at over 9600 baud, even with hardware flow control activated via the AT+FLOW1 command. And even then, if either the BLE module or the phone was moving, data was consistentlydropped.

I ended up implementing an SD data logger instead.


SD card initialization fails randomly I have a SD card reader that is working fine exept that sometimes SD.begin fails for no apparent reason.
To work around this issue I have put the SD.begin in a while loop and then I display the error on my LCD. When the error happens I then remove and reinsert the card witch works usualy on the first or second try. I have never seen any problem ones the card is initilized.
Does anyone has any idea what might be the problem?

I have seen SD cards that do not like this section of code:

  // command to go idle in SPI mode
  while (cardCommand(CMD0, 0) != R1_IDLE_STATE) {
    if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
      error(SD_CARD_ERROR_CMD0);
      goto fail;
    }
  }

Some SD cards (mine, of course) seem to need a little quiet time to finish their INIT process.  Adding a delay of <something> made the INIT process complete successfully, first time through the loop.

I'm guessing that the SD card spends so much time handling the repeated CMD0 commands (continuously sent by above loop) that they don't get to spend time on the INIT process.  IIRC, the standard says the card is allowed to take up to 2 seconds to INIT (!).  I can't recall, but I think I tried 150ms or so:

  // command to go idle in SPI mode
  while (cardCommand(CMD0, 0) != R1_IDLE_STATE) {
    delay( 150 ); // let SD get some time to work
    if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
      error(SD_CARD_ERROR_CMD0);
      goto fail;
    }
  }

I do recall that reinserting the card would sometimes make it work.  I have suggested this to at least one SD card library maintainer, but I think we're all reluctant to impose a delay on all cards.  OTOH, it is just during ::begin.

It might work for you, though.  The above snippet is from SdSpiCard.cpp, but you may have to go looking for it in other places, depending on which library and version you're using.


Is there a way to test whether the UART Tx buffer is empty without waiting? Is there a way to test whether the UART Tx buffer is empty without waiting?

serial.flush() waits, so it won't help me.

I tried looking into serial.SerialEvent(), but the link was broken on the Arduino reference page.

Can anyone point me to a description of it?

It doesn't look like that function is implemented. The source for HardwareSerial.{cpp,h} are in /Applications/Arduino.app/Contents/Resources/Java/hardware/arduino/cores/arduino under OS-X. (Someone better versed in Window than I may have to chime in here to point you to that source location.)

Taking HardwareSerial::available() as a model, create a new function, say, HardwareSerial::txremaining(), that does the same thing, but for the transmit buffer.

Left as an exercise for the student:Make a common function that returns the contents of an arbitrary ring-buffer and use it in both ::available() and ::txremaining().


How to get the signal strength of the network connected with the ESP8266 I am using ESP8266 module with Arduino Uno.I don't know how to get the signal strength of the network with which ESP8266 is connected.Please help..

The page http://tomeko.net/other/ESP8266/ names the following command:

  AT+CWLAP     // list available access points

According to the example given there, this returns a list of items looking like this:

  +CWLAP:(3,"UPC784xxx",-75,"70:54:d2:xx:xx:xx",1)

where "APs are sorted by channel and values are: (security, "name", signal strength, MAC, channel) where for security: 0 = open, 1 = WEP, 3 = WPA, 4 = WPA2".

Thus you can use AT+CWJAP? to obtain the name of the network you're connected to and get the signal strength from the respective item in the list provided by AT+CWLAP.

See http://wiki.iteadstudio.com/ESP8266_Serial_WIFI_Module for a reference of commands.


What is the meaning of the term FQBN? So I'm reading the Platform specification and doing some programming and I'm getting the error:

Error missing FQBN

So what does FQBN mean?

My guess: Fully Qualified Board Name

I.e., a descriptor that uniquely identifies a board and its configuration.


Arduino if else code I have made this If-Then-Else code, but it doesn't work.

First I tough only the analog code is wrong, but if I take a digital port, the code doesn't work either.

What did I do wrong?

int sensorPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0.00001;  // variable to

void setup() {
  pinMode(13, OUTPUT);  //LED BORD UIT
  pinMode(12, OUTPUT);  //LED4
  pinMode(11, OUTPUT);  //LED3
  pinMode(10, OUTPUT);  //LED2
  pinMode(9, OUTPUT);   //LED1
  pinMode(8, OUTPUT);   //Elektro Magneet
  pinMode(A0, INPUT);
}

void loop() {
  if (A0 == HIGH) {
     digitalWrite(13, LOW);
     digitalWrite(12, HIGH);   //LED on, magnet off
     digitalWrite(11, HIGH);
     digitalWrite(10, HIGH);
     digitalWrite(9, HIGH);
     digitalWrite(8, LOW);

  } else {
     digitalWrite(13, LOW);
     digitalWrite(12, LOW);   // LED Off, magnet on
     digitalWrite(11, LOW);
     digitalWrite(10, LOW);
     digitalWrite(9, LOW);
     digitalWrite(8, HIGH);
  }
}

Replace the line:

  if (A0 == HIGH) {

by this one:

  if (digitalRead(A0) == HIGH) {

If you plan on using the pin back as an analog input, use something like this:

  if (analogRead(A0) > 512) {

The explanation is what Ignacio said: you were comparing the pin "name" A0 directly to HIGH instead of reading from the input named A0. To make it clearer, the two lines are equivalent:

if (A0 == HIGH)
if (0 == HIGH)

Get it?

There's more about what pin names to use with digitalRead() and analogRead() here:

analogRead(0) or analogRead(A0) at EE.SE.


Process Sensor Data from Arduino Yun with Python I'm currently working on a small project with my Arduino Yún.
I want to process the sensor data in python and send them in a message queue. I need to use Python3.

I cannot find a way to get the sensor data in my Python code.
I already tried to start the python process in my sketch and use the println method of the process object but this doesn't work.

I also tried to use the BridgeClient class from the Arduino Github but it won't work either.

Summarized:
I can't find a way to send my measurements from my Arduino sketch to the my Python3 program on the Linux side of the Arudino Yún.

I don't think this is an extraordinary problem and I don't understand why there aren't any tutorials for this specific use-case.

The section below contains my Arduino sketch, which does the measurements.

#include <SparkFunHTU21D.h>
#include <Wire.h>

HTU21D myHumidity;

int trigPin = 11;
int echoPin = 12;

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

  myHumidity.begin();

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

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

  //Perform 5 SoilMoisture-measurements and get mean
  float soil = meanSoilMoisture(A0, 5);
  float humd = myHumidity.readHumidity();
  float temp = myHumidity.readTemperature();

  float distance = getDistance();

  String dataString;
  dataString += String(soil) + ", " + String(humd) + ", " + String(temp) + ", " + String(distance);
  Serial.println(dataString);

  delay(4000);
}

long getDistance() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);
  long duration = pulseIn(echoPin, HIGH);

  // Convert the time into a distance
  return (duration/2) / 29.1;     // Divide by 29.1 or multiply by 0.0343
}

float meanSoilMoisture(int analogPin, int nMeasurements) {
  float sum = 0;
  for(int i = 0; i < nMeasurements; i ++) {
    sum = sum + readVH400(analogPin);
    delay(50);
  }

  return sum / nMeasurements;
}

//Perform Measurement
float readVH400(int analogPin) {
  int sensor1DN = analogRead(analogPin);
  float sensorVoltage = sensor1DN*(3.0 / 1023.0);
  float VWC;

  // Calculate VWC
  if(sensorVoltage <= 1.1) {
    VWC = 10*sensorVoltage-1;
  } else if(sensorVoltage > 1.1 && sensorVoltage <= 1.3) {
    VWC = 25*sensorVoltage-17.5;
  } else if(sensorVoltage > 1.3 && sensorVoltage <= 1.82) {
    VWC = 48.08*sensorVoltage-47.5;
  } else if(sensorVoltage > 1.82) {
    VWC = 26.32*sensorVoltage-7.89;
  }
  return(VWC);

}

I'd like to have a way to send dataString to the linux side of the Arduino Yún and process it with Python3.

As explained earlier I've already tried out multiple solutions, e.g. start a new process and use the println method of the process.

{...}
Process proc;
void setup() {
    {...}
    proc.begin("python3 /mnt/sda1/test.py");
    p.runAsynchronously();
    {...}
}
{...}
    proc.println(dataString);
{...}

I've tried to read this dataString in Python3 in different ways, e.g. I've used the input method, because I read in a forum that I can handle such input like a keyboard input.
It didn't work and I didn't get an error, neither in Python nor in my sketch.

I've read different examples using the Bridge library. So I set up the sketch:

{...}
bridge.put("data", dataString);
{...}

I'd like to try out the BridgeClienton the python side but this library was written in Python2. I don't want to migrate the library to Python3 and I need to use Python3, so I didn't find a way to write Python code here.

I would highly appreciate any help from you.

You might want to try the Process method, although, looking at your recent edits to the question, it seems like you already have.

Nevertheless, I was having difficulty getting my head around the problem when I first used my Yún, and I found the information below helped me understand how to get up and running. You do say that you've tried many solutions already, and maybe you've already seen this, but as you don't list which solutions you have already tried (apart from one), I thought it might be worth posting this link as an answer.

From this post to the thread on the Arduino forums, Yun Serial connection between Arduino and Linux

  Accepting HTTP connections, as shown in the Bridge tutorial, is
  but one facet of the Bridge library. (And probably the least useful
  and least efficient facet.) It is intended for accepting incoming
  connections from the greater network, not necessarily the local Linux
  processor.

  The Bridge library is a collection of different classes that perform a
  variety of operations, all over the serial link between the two
  processors, and all can be used at the same time. The Bridge uses a
  network port paradigm, not HTTP. Using ports gives it a little more
  overhead, but it allows multiple simultaneous "connections" between
  the sketch and Linux sides.

  I suggest you take a look at the Process tutorial. It does what
  you want, and 95% of the time it is the only part of the Bridge
  library that I use. The example defines Process objects that are local
  to a function, which run simple commands that do a little bit
  different f processing, return a result, and then exit.

  My projects typically define a global Process object which starts a
  Python script, and keeps the connection open. Once open, the sketch
  can write to the Process object at any time, and the Python script
  reads that data from STDIN. Python can write to STDOUT at any time,
  and the sketch can read it from the Process object. The Process class
  derives from the Stream class, just like Serial, so your sketch can
  use any of the read/write methods you would use for a serial port. On
  the Linux side, you are just reading/writing as you would to the
  console. By default, Pythons runs in a buffered mode: I've found that
  you need to add the -u option to the command line that runs your
  Python script, or add it to the hashbang at the beginning of your
  script.

  There are those who disable the Bridge library, and use the serial
  port manually on both sides. This can be done, but I've not had to
  resort to that yet. The Process class does everything that a direct
  serial connection can do, and more: you can have multiple simultaneous
  Process connections going, and you can still use all of the other
  Bridge library features. If you disable the Bridge library, you get
  just the one connection stream. It would be a bit more efficient, but
  unless you are dealing with high amounts of data, I'll bet you don't
  need to do that.

  My typical project has the sketch running as a rather dumb I/O
  processor, passing barely digested input data down though one or more
  Process objects to a Python script. The Linux side does all of the
  heavy processing and network communications, and then sends output
  data back up the sketch which outputs it to the pins.


Relay feedback control I have a two-relay system set up to a DC motor. So, if I close one relay, the motor moves on one way and if I close the second relay (and open the first) the motor goes on the other direction.

I compare two variables (target inclination and real inclination) if they are not the same I would like to open one of the two relays UNTIL the are the same value.

Both variables are calculated based on inclinometer input and some aritmethics.

I do know how to calculate the variables, how to close the relay based in the comparation of variables and which relay open.

But I don´t know how I can tell to open the relay because the motor has reached target inclination.

How I can recalculate and compare constantly target inclination and real inclination when the relay is closed and the motor moving?
Is this posible on Arduino? Is this multithreading?

Thank you very much, any ideas are welcome!

Answering my own question, I think I found some way to get the solar panel face the sun.

As said before, the inclinometer reads the position and makes some calculations using lookposition() function, then this happens:

void lookforsun() {
  while ((targetElevation + 3) < realElevation | (targetElevation - 3) > realElevation) {

    Serial.println("Elevation is not correct");

    while (realElevation < targetElevation)
    { Serial.println("Moving to south");
      digitalWrite(south, LOW);
      lookposition();
    }
    digitalWrite(south, HIGH);

    while (realElevation > targetElevation)
    { Serial.println("Moving to north");
      digitalWrite(north, LOW);
      lookposition();
    }
    digitalWrite(north, HIGH);
  }

  while ((targetHourangle+3) < realHourangle |  (targetHourangle-3) > realHourangle  ) {

    Serial.print("Hour angle is not correct");
    while (realHourangle > targetHourangle)
    { Serial.println("Moving to east");
      digitalWrite(east, LOW);
      lookposition();
    }
    digitalWrite(east, HIGH);

    while (realHourangle < targetHourangle)
    { Serial.println("Moving to west");
      digitalWrite(west, LOW);
      lookposition();
    }
    digitalWrite(west, HIGH);
  }

As you can see I took the frightening way of nested while loops, but appears to work.

The first while measures if realElevation is between +-3 degrees of targetElevation, if realElevation is far away (target+-3) enters the second while loop, which determines if needs to go up or down.

I included the +-3 because the sensor is so very sensible.

Thank you very much  Russell McMahon and portforwardpodcast for your ideas!


How to use the pushbutton without using if, else I want to let the led blink for 3 seconds then 2 seconds then one second using the button one time and without using if/else

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

void loop() {
    // put your main code here, to run repeatedly:
    digitalRead(5, HIGH);
    digitalWrite(6, HIGH);
    delay(3000);
    digitalWrite(6, LOW);
    digitalWrite(6, HIGH);
    delay(2000);
    digitalWrite(6, LOW);
    digitalWrite(6, HIGH);
    delay(1000);
}

As the required operation is finite and short, you can just hard code the sequence.


How do I know if I need to use a resistor in a circuit? I have been trying to find answers on Google to this question but cannot seem to find any answers that actually pertain to what I am wanting to know.  I would consider myself a beginner in the area of electronics having some experience but not understanding how everything comes together outside of the some of the basics.  What I am wondering is this; How can I tell if I need to use a resistor in a circuit?  More specifically, When I am hooking sensors up to an Arduino, how can I determine if I need resistors in the circuit?  Anywhere I look I typically see the default LED/Resistor example but that is not helpful.  It doesn't explain how Arduino/Raspberry PI modules and sensors fit into the equation.  I know the data sheets for the various modules/sensors explain how much current is needed/used by the device but how do I take that and apply it to an Arduino circuit?  Thanks in advance.

How can I tell if I need to use a resistor in a circuit?

You can tell because the circuit includes a resistor.

If a circuit needs a resistor the circuit diagram will include a resistor. If it doesn't, then it won't.

The circuit for connecting an LED to an Arduino consists of an Arduino, an LED and a resistor.  Because of that you know it needs a resistor. Because it says it needs a resistor.

A resistor drops a certain voltage across it when a specific current flows through it (Read up on Ohm's Law...). If you need to drop a specific voltage with a specific known current, or if you need to cause a specific current to flow with a fixed voltage, then you use a resistor for that job.

You don't just throw resistors willy-nilly into every circuit you make simply because you see one being used with an LED.

If a device says it runs off 5V and uses 300mA current then you know that you need to hook it up to a power source that is 5V. You also know that the module will use up to 300mA of current from that source, so your source has to be capable of providing at least that much current.