body:
I need a motor controller for a 24v motor and I want to control it using än Arduino Uno. Suggestions?

The motor needs to run both directions and is going to draw about 5A

title: Motor controller for 24v motor, Arduino Uno

Answers: 3

body:
I'm doing my own driver dude using Tip122 but you can use TIP120 too [TIP][1]and other components
[![TIP122 driver][2]][2]

  [1]: https://www.fairchildsemi.com/datasheets/TI/TIP120.pdf
  [2]: https://i.stack.imgur.com/WD5Bx.gif

body:
try this [Arduino Compatible Mega Motor Shield][1]. Specs:

 1. Low-cost robust H-bridge ''shield'' for Arduino
 2. Provides the ability to control up to 30A of current at up to 28V
 3. Supply voltage: 5V to 28V (24V max battery rating)
 4. Continuous output current: 13A
Have, a look:

  [1]: http://www.robotshop.com/en/arduino-compatible-mega-motor-shield-1a-5-28v.html

body: better invest few dollars and use a motor controller that will keep you from shooting threw the MOSFET transistors, enable soft start of motor and let you select between fast decay and slow decay when PWM is in OFF state. ( see details for DRV8814 by TI)


body:
I've noticed that on the back of an Arduino PRO mini are two Jumpers next to the `A4` and `A5` pins, marked with red in the following :

[![Pro mini Back view with jumpers selection][1]][1]

Looking at the leads one seems to be a bypass for the POWER Led and the other a bypass for the regulator, but not sure.

Further, the schematic reveals just one Jumper `SJ1` :

[![Arduino Pro mini - Power schematic with jumper selection][2]][2]

https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/Arduino-Pro-Mini-v14.pdf

So, my questions are :

1. Why are there two physical Jumpers on the board ?
2. Are these two jumpers actually just one : `SJ1` ?
3. And if so how to connect them in order to enable `Power isolation` ?

  [1]: https://i.stack.imgur.com/358z0.png
  [2]: https://i.stack.imgur.com/GCJcp.png

title: Arduino PRO Mini - The pads [was "jumpers"] on the back and Low Power Consumption

Answers: 4

body:
I think those aren't jumpers, but pads to place two pull-up resistors for I2C.

It seems the eagle files Sparkfun shares aren't the same as the board in the picture.

But you don't need to worry about this. If the RAW pin is not connected the MIC5205 regulator uses only 0.01μA according to the datasheet.

body: These pads are not jumper SJ1. On the front of the board just beneath the GND pad there is a blob of solder. This is SJ1 (I believe - I am writing from memory, I do not have a Pro Mini sitting on my desk at the minute) and removing the solder blob will disconnect the LED and output of the regulator from Vcc.

body:
Both responses are correct but be mindful that this is a SparkFun feature.  An Arduino Pro Mini from China won't necessarily have the `SJ1` pad.

1) Like Gerben said, the pads on the underside of the board are for I2C pull-up resistors.

2) Like David said, `SJ1` is on the top of the board next to the `GND` and `RST` pins.  (It looks like a small solder blob.)

3) To isolate the regulator from `VCC`, remove the solder blob on the top of the board with a sucker or solder wick.

The Sparkfun schematic shows all of these elements:
https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/Arduino-Pro-Mini-v14.pdf

body:
You can look up the location of SJ1 in the [Eagle project files](https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/Arduino-Pro-Mini-v14.zip) that are provided by [Sparkfun](https://www.sparkfun.com/products/11114)). For example, you can import them into [KiCad](https://www.kicad.org) (Free and Open Source), which opens a PCB and a Schematic editor.

To locate SJ1 you can simply click on it in the Schematic editor such that it's highlighted in the PBC editor, as well. For better overview, you may want to hide all the layers besides the foreground one (e.g. 'F.Cu') and click View/Zoom-to-Fit:

-> That means SJ1 is located on the front of the board, right of pin 9 (ground), i.e. it's highlighted in a lighter red. For comparison, I included an image (Sparkfun, CC BY 2.0) of the front, where you can see that SJ1 is marked by a white rectangle (painted on the board) and that it's closed, by default by a solder blob, which can be de-soldered (e.g. using solder wick and a bit of flux).

---

NB: To enable power isolation (i.e. such that the MCU can be directly powered without also powering the power-on LED and one side of the on-board LDO, e.g. in order to save power), you have to open SJ1.

---

Thus, the pads on the back of the board, you marked in an image you included in the question, are something different. In KiCad you can look them up as well: that means switch to the back layer (e.g. 'B.Cu') and click on the pads such that the related parts are highlighted in the schematic editor:


body:
The **LED_UPDATE()** is called in my **loop()** function, I implemented it (tried anyways),
to send sms as shown in the code such that  only one sms is sent , because as the **loop()** keeps calling **LED_UPDATE()**, it's going to keep sending an sms every time (yep you guessed it, very bad for credit :o )

any tips on how I can get around this or what i'm doing wrong in my code would be much appreciated.

**p.s.** nearly left my mobile phone in the code lol

    void LED_UPDATE(int state)
    {

    int count; // initialized to zero, once program runs it automatically enter state ==1
    if (state == 1)
    {

        digitalWrite(RED_PIN, LOW);
        digitalWrite(GREEN_PIN, HIGH);
        count=0;
    }
    else if (state == 2)
    {
      count+=1;
      Red_Blink();

      if(count == 1 )
      {
        sms.SendSMS("086XXXXXXX", "PANIC BUTTON PRESSED, Subject needs help!!!");
      }

    }

title: Arduino to send sms one time only when a button is pressed

Answers: 1

body:
You are resetting `count` every time you enter the function.

    static int count; // initialized to zero, once.

Adding the static statement should initialise the variable once and preserve its value between calls.


body:
I'm looking to minimise the parts count and the power consumption as much as possible and I was wondering if is it possible to store a variable or execute a method when the 'reset' button is pressed?

<strike>I didn't find any docs or hints regarding this.</strike>

In theory, can it be done with an interrupt?

### Edit

In a further research Atmel shows, that if you burn the 'RSTDISBL' fuse (still in theory for me) you can get hold of the reset button by transforming it in a I/O pin with "special" electric characteristics:

[![Atmega 382 reset short description focus ][1]][1]

Also, if you look at the schematic the reset pin shows that it has what it needs to be an I/O pin:

[![enter image description here][2]][2]

I say in theory because I really don't know if arduino has the required constellation for this capability and if it comes whit the fuses already burned.

  [1]: https://i.stack.imgur.com/RFOm8.jpg
  [2]: https://i.stack.imgur.com/O0qOz.jpg

title: Reset as I/O pin

Answers: 1

body:
Yes, there are several possibilities here.

One is detecting state after reset and acting on it.  One of the reasons you might do that would be to shut the processor down all but completely, and let the reset wake it back up.

Another would be to program the reset disable fuse and repurpose it as an I/O pin - of course if you do that, you can only then reprogram the chip if you have implement working functionality to get back to the bootloader (or similar), or if you use a high voltage programmer.

These are in the category of things which make development a lot more difficult, but are sometimes worthwhile as they let you squeeze a little more capability out of the hardware.  If you are just starting a design, you might consider a different chip instead - but if you have existing boards or design investment, and this lets you get the last little bit of needed capability from it, it is possible.


body:
My kids got many fluffy toys, and I would like to make them move and talk. Something like a small platform with wheels and a speaker and some sensors that I would be able to mount any of the toys on.

I'd like to build something like 2 platforms with motors and sensors that move around, and when encountering obstacles "bark" at them through the speakers, wait random number of seconds, and move in different directions. Then the kids would mount their favorite fluffy dogs/cats/bears/rabbits on top of these platforms and unleash them on each other.

I am very new to DIY; what do I need to buy for such a project?

title: What do I need to make fluffy toys move and talk?

Answers: 2

body:
You will need a processor board, motor driver, sensors, and audio amplifier.

Since you are asking on the Arduino forum, it would be natural to consider one of the Arduino boards or derivates - but beware they tend to be rather antiquated compared to alternatives now available.  The plus side of the classic ATmega boards is the wide variety of read-to-go example code available right within the IDE, and the wide supply voltage range (of the bare chips if not the boards) which is more compatible with AA-cell battery packs than competing device's narrower voltage range tends to be.  The one part of the functionality you describe that is a bit of an issue is the audio output - you can get it from an ATmega but it will be poor in quality and you will need to add storage for the "bark" data.  You might almost consider a separate module with an ATtiny and a small SD card for that (ironically the ATtiny while generally less capable has fast PWM better suited to audio).

For motor drivers, especially when using batteries steer clear of the older bipolar L293/L298 type of solutions, as these have very high internal loss which basically means that one cell in your battery pack exists just to generate heat in the driver IC.  A modern FET based driver (the TB6612FNG is quite popular) will be better.

For sensors you probably want one or more of microswitches extended with "whiskers", ultrasonic rangefinders, or short range IR reflectance.

Some dual wheel drive (or "tank steering") RC toys can be worth considering as platforms, but their gearing may be too fast for your purposes, particularly those designed to spin and tumble.  Continuous rotation servos are sometimes mentioned, but it can be hard to get them tuned to not rotate when commanded to stop, and mounting wheels can be tricky.  The small plastic gearboxes work well if you can get matching wheels but are hard themselves to mount.  Access to a 3d printer can be quite useful for creating missing physical components, though a block of wood and a router can make a nice chassis, too.  You can also buy ready made Arduino robot base kits with chassis, gearboxes, and wheels.

For audio output, you can accomplish something with an NPN transistor and base resistor driving a speaker, but best results would be with a small class D driver board as are now widely sold for a few dollars.  They tend to be stereo, but you can feed both sides with the same signal.  If you only wanted "robot beeps" you can drive a piezo disk directly from a processor pin with reasonable loudness at higher frequencies, but the low frequency response is quite poor.

body:
**Don't do it.**
----------------

When you say to us:

> I am very new to DIY; what do I need to buy for such a project?

Then you really aren't ready yet.  Sometimes a virtuoso or savant exists, and they can make incredible DIY projects, but for most people, jumping into such an aggressive project as your first DIY is a recipe for disaster.

I'm not trying to be a smart-ass or negative, but you should get an Arduino and try some PROTOTYPING first.  Again, not trying to be a smart-ass, but if you even have to ask this question, then you really aren't ready yet.

When I work with people on their first project, you should see how excited they get when they can get a light to blink (I still get excited each time too)!

I think you should go for more of a "karate kid" approach: Wax the car, paint the fence, sand the floor.  Once you know the fundamentals, you'll be a ninja before you know it.

I could list a pile of "fundamentals" here, but any other guide would be more comprehensive than my Arduino karate kid list.


body:
I have been trying to use my newly bought L293d Motor Driver Module to run motors(a single motor in this test case, simple 5V toy motor) from my Arduino UNO. Thing is, this is an entire module, not just the IC (in which case there are many tutorials available). So I was following this tutorial to try and get my motor running.

Here is the tutorial - http://www.instructables.com/id/Arduino-and-L293D-Robot-Part-1-/?ALLSTEPS
Here's what the module looks like - [![The module][1]][1]

There are 6 Pins on the module, which bring out the 6 inputs, EN1, EN2, IN1, IN2, IN3, IN4. Now since I am using only one motor, I connected my motor to the OUTPUT 1 & 2 header given on the module. I then take the 5V and GND from Arduino and connect them to my Module's 5V and GND header, (leaving the 12V one empty), I thought that this would be enough as my motor is also of 5V.
I then connected the IN1 and IN2 to the pins 7 & 8 on my Arduino and used the following code-

    // Simple code to make the motor turn
    int RightMotorForward = 7;
    int RightMotorReverse = 8;

    void setup()
    {
      pinMode(RightMotorForward, OUTPUT);
      pinMode(RightMotorReverse, OUTPUT);
    }

    void loop()

    {
       digitalWrite(RightMotorForward, HIGH);
       delay(10000);

       digitalWrite(RightMotorForward,LOW);
       delay(1000);
    }

Nothing happened. The motor didn't work and I have no idea why. I've gone through the entire datasheet for L293D but I found nothing that could help me. I suspect that it has something to do with the EN1 pin, but I don't really know how to use it, the tutorial said to connect it to 5V, which I tried but no results. So where am I making the mistake? How do I get this to work?

  [1]: https://i.stack.imgur.com/DoTMM.jpg

title: Using a L2938D Motor Driver Module. (Not IC, Module)

Answers: 2

body:
While no one can tell you exactly how to connect that board without having its documentation or the board in hand to examine visually or with an ohm-meter, it is quite likely that by leaving the "12v" terminal unconnected, no power is being provided to the motor side of the circuit.

It kind of looks like there is a voltage regulator on board, so it may be that it will even provide 5v on that terminal when given something 7 volts (or so) or higher on the "12v" terminal - again, we cannot know without details of your exact board.

The L293 is an old and low-performing chip, with internal losses that mean  that to achieve 5 volts across a motor, you will need to supply very nearly 7 volts to the chip.  The difference gets wasted as heat.

body:
ooops. That **5V** you are applying to **5V pin** is actually an output pin.

You must apply some input voltage at the **12V** & **GND** inputs.

Don't forget to remove that **5V** connection to **5V pin**


body: I am working on wearable project using an Adafruit Flora V2, and for this project I need to use the onboard NeoPixel. I also need to use Neopixels that are attached to the D6 pin (is it a pin?). I have a line at the beginning of my program that says `#define PIN 6`. I found that I can use the onboard NeoPixel by changing this to `#define PIN 8`. Is there a way to use the onboard NeoPixel <b>and</b> the ones attached to D6. I already have everything wired up, and the rest of my program is written, I just need to use both pins. Thanks for any possible help.

title: Adafruit Flora V2 use onboard and external NeoPixels

Answers: 1

body:
The #define is just letting you use a nice name for the numeric value of the pin.  If you want to use two different pins, you use two different names.

So you might define them at the beginning something like:

    #define BOARDLED 8
    #define STRIPLED 6

Then you create a NeoPixel object that uses that pin.  In your case, you'll do this twice.

    Adafruit_NeoPixel flora_led = Adafruit_NeoPixel(60, BOARDLED, NEO_GRB + NEO_KHZ800);
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, STRIPLED, NEO_GRB + NEO_KHZ800);

And then you call the one you want to set/modify/show/etc.

    strip.show();
    flora_led.show();


body:
I am hoping I could get some help developing a an idea I have for archaeologists/soil scientists using an arduino and the TCS3200 colour sensor. The idea I have is a simple device which can determine munsell colours with more accuracy and speed. The current conventional method is to use colour chips/swatches found in the Munsell system booklet and match them as close to examples of sediment/soil found at archaeological sites. The problem with doing this method is that it is highly subjective, and time consuming.

My idea is to use the Adafruit TCS34725 to read and detect the RGB colour of the sediment (in the RBG colour space) and convert the data into the Munsell System. I have all the data of what RGB ratio corresponds to each Munsell colour -- which I have downloaded from this site: [www.cis.rit.edu/research/mcsl2/online/real_sRGB.xls][1]

My problem is that when I use the sketch provided, I can not figure out how to use the "if" statement to "Serial.print" what the munsell colour corresponds to the RGB colour detected by the sensor.

My ultimate goal is to modify the colour view sketch here [see: colorview][2]
I would like to keep the everything provided but change two things, I would like to convert RGB into Munsell using the data provided by the RIT link and also add a screen and button to start the read process and display the colour.

If some one would be willing to help me that would be great!,

  [1]: http://www.cis.rit.edu/research/mcsl2/online/real_sRGB.xls
  [2]: https://github.com/adafruit/Adafruit_TCS34725/tree/master/examples

title: Converting RGB from color sensor into the Munsell Color System

Answers: 1

body:
I have some thoughts on your task. First of all colorimetry is a science on its own. I know people working in this field for decades with equipment costing many millions of €. They all share some basic wise words. One is: "Because we all see colours we think measuring colous is an easy task. The opposite is true. Many of the best colorimetrists are colour blind." One second is: "Without light there is no colour". I will write on this later.

Colorimetry in fact is a complex matter. Between a colored piece of stone and a numerical value normally lie a lot of transformations and convolutions. And inbetween there are also lurking many error sources.

This said, I'm sure it will be possible to produce somewhat acceptable results with your sensor. Provided you do a proper calibration and add a calibratable light source.

Speaking of light source. A piece of stone can only reflect incident light (except some uranium/radium salts, you don't want to deal with). Pigments are basically LTI-systems (aka passive filters). This means they can only reflect wavelengths which are present in the incident light. And the will reflect a well defined and individual proportion of each wavelength regardless the luminous flux of the incident light. This means, if your incident light contains nearly no blue light then the stone or whatever you want to examine will reflect only the fraction of "nearly no light" it typically does reflect of any amount of blue light.

So the remission spectra of all pigments get shaped (multiplied) by the spectrum of the incident light. Your sensor sees only the reflected light and therefore will give totally different results for one and the same object depending on the incident light. Look up the spectra for daylight and incandescent light and think about the results of your sensor.

To make a long story short, you can only yield reproducable measurements if you supply your own light source along with the sensor. This is in fact the way all colour meters work.
The only other way was to measure the full spectrum of the incident light. Reasonable portable spectroradiometers for this purpose cost 5000 €. So it's better to go for a light source :).

As they are rather affordable I recommend using LEDs to make up a light source for examination. But LEDs suffer from several drawbacks. They tend to change their output spectrum with their chip temperature and ageing processes. So you have to supply a proper calibration procedure for your measuring equipment. And you better do the calibration sequence before every measurement.

You then have to design an apparatus which allows the light from your LED fall onto your samples (stones, sediments or so) but prevents other scattered or direct light to enter your sensor. Otherwise all measurements will be crap.

While this is not a direct answer to your question, I think the topic is important enough to write an elaborate pamphlet.

**Update**

Now some more words more closely related to your problem.

In general loading a huge excel table into your arduino is not necessarily a good idea, even if a big "if"-code array was possible. Storage is scarce on this platform.

If you combine a lookup table with interpolation, you can save much space. You would have to omit 90% of all datapoints and estimate all in between when measuring. Still the table will be rather big, because you have three degrees of freedom.

Another drawback of big tables and LUT with interpolation is, that it makes calibration difficult. Normally, when you calibrate your sensor, you have to adjust the parameters along the calculation. If you rely on a table, you have to exchange the whole table, regardless if it is something like that excel thingy or a condensed lookup table.

If you go for an analytical solution, as suggested in one comment, the number of parameters you have to update after calibration reduces drastically. Effectively you have to adjust some factors and offsets in the equations for this problem. Of course you will have to learn the ropes of the photometric equations, but you will  have to do that anyway, I think.

Some more words on the design of your appartus. Your idea of a cylinder in front of your probe is good. I recommend to fit it with a rim of black foam rubber, so you can seal light coming from outside. And you have to paint the inside of your cylinder as black as you can. See the interiour of a camera objective for reference.

If it is white you will have multiple reflections and multiple filtering which deteriorates your measurement results vastly.


body:
Ok, so i'm trying to make [This Project][1] and the code comes all in different .ino files but in the video its all in one program. So how do I compile all of the code onto the arduino? (By the way the code is on step 5 in a .zip file) Thank you!

  [1]: http://www.instructables.com/id/AbHhGD-the-Arduino-Based-Hand-held-Gaming-Device/?ALLSTEPS

title: Help compiling multiple .ino file code with code! (I'm not sure what to name this)

Answers: 1

body:
One of the .ino files is likely the main code file.  Name the enclosing folder with the name of the .ino file, then compile it as normal.

In this case, AbHhGD.ino is the main file, and its folder should be named 'AbHhGD'

The comments indicate there are missing libraries you likely need to install.


body:
I have a problem collecting data from my accelerometer/gyroscope sensor with a constant sampling rate. Is there a way to program the arduino to collect data from the sensor and store these values in a SD card with a constant frequency of 1kHz without using delay? The sensor that I am using is a MPU6050 gy-521 sensor that uses I2C with arduino. I will be reading 6 different datas from my sensor: acceleration in x,y,z directions and gyration in x,y,z directions. Thank you all in advance for the advice/help.

so my project will be making a device that collects the values from the sensors and saves them to study the data later. First, a LCD display will print out a message without having any data collection to occur. The data collection will start when a button is pushed. After the button is pushed, the display will print out another message saying that the arduino is collecting data and the Arduino will save the 6 values (x,y,z acceleration and gyration) from the accelerometer/gyroscope sensor to the SD card. The data collection will stop after the button is clicked again and the display will print out another message saying that it has stopped collecting data. Then, this process can start again if the button is clicked once again. Thanks in advance

title: sensor sampling frequency

Answers: 2

body:
You have discovered delay() does not guarantee the period of your code.  This is because the period of your code is the delay() plus the time for your code to execute.

What you need is a hardware clock to give your code an indication that a fixed period has expired.  [This][1] is one of several Arduino timer libraries. The timer library web page describes your problem in more detail with example code using delays and using the timer library features.

  [1]: http://playground.arduino.cc/Code/Timer

body:
A quick and dirty solution is to just the right the code that does the sampling and loop it, say 10,000 times, with a short delay.  Measure the time it takes to do the 10,000 samples by recording time before and after all the samples.

The amount of time taken will be:

    10,000 x (delay period -> known) + 10,000 x (actual amount of time to do the sampling)

From this data you can determine the required delay to get your 1 kHz sampling goal.


body:
I'm using a MAX7219 and 6 (six) seven segment displays
I used my own board and two purchased on ebay - no difference in operation.
MOSI, and CLK are correct and verified with my scope (Tektronics)
CS (chip select) is pin 22 (for no particular reason) SPI is set to Mode0
Yes, I have tried other pins as CS - all work the same.
My MEGA board can be powered by USB or 9.9 VDC wall-wart - no difference
Trial code is shown below, and works properly.
Placed 47 uF 50V cap on display board between +5 and GND - no effect
Placed 220 uF 35V cap on display board between +5 and GND - no effect
MOSI, SCK and CS are verified with scope to be 5 VDC. Compiler and D/L applications are set to MEGA and seem to work properly.

**PROBLEM IS THIS:**
Code compiles and D/L properly into Mega. Mega resets, and about 50% of the time all digits illuminate (not executing code properly?) Digit 0 (most right hand digit is enabled) never works. I can press the reset on the Mega as many times as I want - no effect.

**HOWEVER** if I pull either +5 or GND to the MAX7219 module, and reset my Mega, it works perfectly. Yes, this is obviously a reset problem, but I've never seen a reset problem before with the MAX7219. I put delays at the beginning at short delays in the SPI communications to no effect.

Has anyone ever seen anything like this before? I have no hair left to pull. I'm thinking maybe to use a MOSFET to turn the MAX7219 on after the MEGA is up and running. Any suggestions are appreciated.

<!-- language-all: lang-cpp -->

     //version 0.1
     #include <SPI.h>
     #define LOAD_PIN 22

     void maxTransfer(uint8_t address, uint8_t value) {

     digitalWrite(LOAD_PIN, LOW);      // Ensure LOAD/CS is enabled (LOW)
     SPI.transfer(address);            // Send the register address
     SPI.transfer(value);              // Send the value
     digitalWrite(LOAD_PIN, HIGH);     // Tell chip to toggle in data

    }

    void setup() {

     pinMode(LOAD_PIN, OUTPUT);          // Set port pin to output

         // Reverse the SPI transfer to send the MSB first
     SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));

         // Start SPI with attributes in "SPI.beginTransaction"
    delay(250);
    SPI.begin();
     maxTransfer(0x09, 0xFF);           // Enable mode B
     maxTransfer(0x0A, 0x0F);           // Use highest intensity
     maxTransfer(0x0B, 0x00);           // Only scan digit 0
     maxTransfer(0x0C, 0x01);           // Turn on chip
    }

    void loop() {

      // Loop through each code
      for (uint8_t i = 0; i < 0x10; ++i)
      {
        maxTransfer(0x01, i);
        delay(50);
      }
    }

title: Arduinino & Max7219

Answers: 0


body:
I was trying to use my L293D motor driver module. But when I upload the following sketch to try and run my motor, but it would get stuck on "Uploading". This happens with this sketch only, and happens randomly, with odds of happening being 3 in 5 times. After a bit fiddling around I found an error
>Programmer is not responding.

When I try to reset the board or just reconnect it to my PC it might work.
Here's the sketch-

    int RightMotorForward = 12;
    int RightMotorReverse = 13;

    void setup()
    {
      pinMode(RightMotorForward, OUTPUT);
      pinMode(RightMotorReverse, OUTPUT);
    }

    void loop()

    {
       digitalWrite(RightMotorForward, HIGH);
       delay(10000);

       digitalWrite(RightMotorForward,LOW);
       delay(1000);
    }

Can anybody point out where I am going wrong? I am using Arduino UNO. Is this just some problem in my code?

title: Arduino IDE get stuck while uploading sketch

Answers: 2

body:
Is the motor driver connected to the Arduino while you program it?

When the Arduino is reset, the output pins on the Arduino are driven high. If too much current is drawn though any of these pins, then the voltage supply to the ATMega328 may drop, and the ATMega328 gets stuck in a brownout.

body: Found the solution... Just connect the 5v from arduino to the 5v on the Module. Then another battery (12-36 V, I tried a 9v one... it worked but only for about 40 seconds), to the 12 V input, keeping the ground common... That's gonna make the motors run!


body:
I'm looking to connect an 8-relay board to an Arduino Uno. A board [like this one][1]. However, I don't really want to use up 8 digital outputs if I don't have to. Is there some intermediate circuitry I can either buy or build that would do this?

For example, can I connect something to the serial so that sending '3' would result in binary 00000011 and thus turn on relay's 1 and 2?

Alternately, and probably more lazy, is there an extension board that would just give me a pile more digital pins?

  [1]: http://www.ebay.com/itm/221389425632

title: How can I connect an 8-relay board without using 8 digital pins?

Answers: 3

body:
A likely solution is to use the Arduino SPI interface and the Arduino SPI [library][1] to control a SPI relay board.  [Here][2] is a 6 year old thread talking about such a board. And [another][3] more recent relay thread where SPI is brought up.

  [1]: https://www.arduino.cc/en/Reference/SPI
  [2]: http://forum.arduino.cc/index.php?topic=8209.0
  [3]: http://forum.arduino.cc/index.php?topic=293858.0

body:
You can use a MUX/DEMUX. Check out the link. Basically, you can select the output pin by a series of commands that you can do with the Arduino. The relay inputs will be hooked up to the IC's outputs

https://www.sparkfun.com/datasheets/IC/cd74hc4067.pdf

body:
There are ICs that provide additional I/O ports through either the SPI or I2C busses, such as  [MCP23017][1] or [MCP23018][2] or their 8 port equivalents.
There are many different makes, search Google for "Arduino addition IO Pins"

  [1]: http://www.microchip.com/wwwproducts/en/en023499
  [2]: http://www.microchip.com/wwwproducts/en/en537375


body:
I would like to use Arduino to control locks around a building which is 5 storeys high and on every floor there is 2 door.

I'm concerned whether the wires is able to travel all the way from the ground floor to the 5th floor to provide enough power to the relay located at the door.

The lock will be a 12V magnetic lock and it will be unlocked thru a SSR relay which will be controlled by the arduino

title: Arduino IO long distance travel

Answers: 3

body:
Yes, losses in wires are proportional to the length, so an excessively long wire may not be able to deliver enough power. Many factors come into play here:

- higher current consumed by the relay increases the losses
- smaller wire diameter increses the losses
- the voltage required by your relay defines how much you can afford to lose

For example, a pair of [AWG23](https://en.wikipedia.org/wiki/American_wire_gauge) wires 30m long will have a total resistance of 4 Ohm. If your relay consumes 100 mA, you will lose 0.4V in the wires. If Arduino delivers 5V, and the relay requires a mininum of 4.5V to work, you're just good enough: you're delivering 4.6V to the relay after the losses.

body:
You are addressing a device control problem that auto, home and building automation has concerned itself with for years.

As such there are many solutions.  Most require a transmitter and one or more receiver(s). [C-BUS][1] is one such solution.  Another is [CAN-BUS][2].

  [1]: https://en.wikipedia.org/wiki/C-Bus_(protocol)
  [2]: https://en.wikipedia.org/wiki/CAN_bus

body:
Use wireless nodes which are self-powered. It is easier (no need for lot of cables) and also solves this issue completely.

You can use [ZigBee][1], which is mesh network. Every node re-transmit signal for nodes which are far. Because you have one on every floor, you would not have issues with reception.

EDIT:
If you want to use wires, I would still keep self-powered nodes and you can communicate with them using i2c or similar. You would need only 3 wires (SDA, SCL and GND) and they could be very thin, because they transfer only signals (<1mA range)). These 3 wires would connect all nodes. All nodes should have distinct address. I think this could be very cheap because you can create nodes with arduino micro which can be bought for ~1.5$ each.

  [1]: https://en.wikipedia.org/wiki/ZigBee


body:
I'm doing an rfid project that requires a read range of at least 5 inches or about 13cm.  I'm using a nano with a usb port, a rfid reader from priority 1 design and a large antenna. The problem I'm running in to is that when I power the project from the usb port I get a pretty decent read range of 11-13cm. But when I power the project from a DC power supply the read range drops considerably.

After a lot of testing with various power supplies I believe that all my power adaptors are dirty enough to cause rf interference and reduce the range.  Powering the project with a 9v battery and a 5v power regulator gives me really good range: 18cm with the largest antenna.  But I need plug in power.

So how can I power this project in a way that gives me ultra clean power?

1. I tried that same 5v regulator with a 5v adaptor and still had short read range.

2. Someone suggested adding a smoothing capacitor between V+ and Gnd but I wouldn't know what size.  I'm not an EE - I'm just a coder with a soldering iron.

3. Is there a better power supply I can get?

[EDIT] Also just FYI, when I connect even only the ground wire the the computers USB port I get a much farther read range. So..

4. Could it be a case of needing to ground the circut better as the switching power supplies only have 2 prongs and probably no real "ground". (Or am I making stuff up?)

[EDIT 2] What about a rechargable situation where my wall adaptor keeps a litium charged and the litium supplies clean power to the circuit?

Also I now know that I can charge my whole circuit with anything from 5 to 12 volts. In fact it would be better to have more in the 7 to 12 range than strictly 5v.

[UPDATE 3] Since this project is in my wall I was able to ground essentially to "earth" and that cleared up the noise. See this question as well: https://electronics.stackexchange.com/questions/230024/grounding-dc-project-to-clean-rf-noise

title: How can I get ultra clean dc wall power for my arduino project?

Answers: 2

body:
This is what I use, although admittedly not in your application. I run it from a 12V wall adaptor and adjust the output voltage to suit my requirements. The input should ideally be at least a couple of volts above the output(depends on current and temperature at 25degC and 20mA it's > 1.6V and 1.5A at the same temp it's > 2.7V).

[![Circuit Diagram][1]][1]

  [1]: https://i.stack.imgur.com/qfyen.jpg

Another alternative if you want to really go to town would be to repurpose an old computer ATX or similar PSU. There are plenty of guides out there and it's a straightforward job.

body: I think the problem is not the voltage but the magnetic field, so maybe better to use a faraday cage (a metal box) around the power supply and connect it to output DC ground.


body:
Coming from a C# background where I do logs for every application, and given that I will be using the Mega for most projects and therefore have the memory available to do so, I want to incorporate error logging in my projects.

What is the best way to do so? Writing to an SD card? Writing via Wi-Fi or Ethernet to a networked storage or PC? Writing to a USB thumb drive?

The current project I am working on uses the Adafruit Music Maker shield so has the SD card reader incorporated into it, so the easy choice there would be to use that but I like creating solutions that are portable to multiple projects so writing via Wi-Fi or Ethernet seems to be the preferred method?

Since I am not fully up to speed with C++, and I see there are various ways to write to text files in C++, are there any preferred ways to do so depending on which storage route I take?

title: Proper error logging using Arduino

Answers: 4

body:
Normally, because Arduino is meant to be easy to understand and use, C++ is only used (extensively) in the libraries.  Perhaps someone knows more about the Mega, but, in general, the Arduino platform does not contain many complex built in features.  For instance, before even thinking about how best to write to an SDCard, you need to do some research into how to load and use the [Arduino SDCard library][1].

[This][2] appears to be what you eventually want to do.

  [1]: https://www.arduino.cc/en/Reference/SD
  [2]: http://www.allaboutcircuits.com/projects/reading-and-writing-files-from-an-sd-card-with-an-arduino/

body:
What you ask is difficult to answer in generic way, because not all the Arduino boards have the same HW options and even if you were to require a certain interface (ex: WiFi), that will introduce other side effects:

 - it will use certain pins/buses (SPI) that one might want to reserve for other purposes (yes you can have multiple peripherals on the SPI bus, but it will require additional code)
 - it might significantly alter the execution timing in certain cases

What most people use - and seem to be happy with - is the serial port:

 - it is not too difficult to setup
 - the ide already has a serial port monitor
 - it can produce information that is immediately human-parsable
 - there is no need to retrieve it afterwards (an SD card has to be extracted, mounted, etc.)

I would advise you to consider this at least as option, if not the only option.

Of course each option has drawbacks: the serial port can also cause delays in the execution, might not be too good if you have lots of stuff to log, etc.

The serial port could be seen as a intermediate step toward wireless logging: modules like the [esp8266][1] do rely on serial communication.

Which means you could have wired logging while in the early phase and wireless logging later on, assuming you can afford to have something constantly listening to your project.

I would consider the SD card only for cases where the device will run unattended for long periods of time and there might be some hard to reproduce event that you want to track.

You could also consider the onboard flash, if you have to log events that happen seldom.

  [1]: https://learn.sparkfun.com/tutorials/esp8266-thing-hookup-guide/installing-the-esp8266-arduino-addon

body:
Embedded systems typically use UART for logging, and Arduino is no exception. Logging to UART is as easy as calling `Serial.begin()` in the `setup()` and `Serial.println()` in the `loop()`, it works on all Arduinos, doesn't require any additional hardware and consumes much less resources than the SD card or networking library. Of course, you're limited in bandwidth (115200 kbit/s, sometimes more), so you won't be able to log in the fast-running cycles.

If you don't like the Serial Monitor feature of Arduino IDE, you can install [one of the many terminal programs](https://electronics.stackexchange.com/questions/52659/hyper-terminal-equivalent-in-windows-8) which will happily write the data from serial port to a log file. Some of these tools also have nice analysis features, including plotting of logged signals, formatting, data conversions etc.

If you're good with command line, creating a log file is as simple as

    cat /dev/ttyUSB0 > log.txt

in Linux or

    type COM1 > log.txt

in Windows.

body:
In my Arduino project, I wrote communication sub protocol between a Raspberry Pi (or a PC).

I simply added some commands to duo vars or arrays into memory.


body:
I have no UARTs left on the ATmega and need to deliver 1 Byte of information from the pi using 1 analog input. I2C is no option either.

I planned using the digital output to request an analog signal from the Pi, but it does not seem to have a DAC.

Is it possible to properly translate/read a PWM signal with the atmegas ADC?
Analyzing the PWM the 'usual' way would probably be too slow as I don't trust the pi to keep up with a high PWM frequency.

PINS left: PA0(ADC0|PCINT0), PD7(OC2A|PCINT31)

I should add that this is a rather large robotics project involving communication between 8 MCUs in it's current state and needs to be extended by a computer vision module(=pi), which is not compatible with the existing custom bus

Edit: This also is a real time system which has approximately ~1-2ms left in it's main loop(10ms period). The required data has to be present in time as it alters the robot's behaviour for this loop.

title: Pi3 + ATmega644P: How do I establish a data connection with 1 analog input and 1 digital output left on the AT?

Answers: 2

body:
You can start researching about one wire protocol [here][1] to see if can implement it given your situation.

  [1]: https://en.wikipedia.org/wiki/1-Wire

body:
The solution was to hook up PA0 to GPIO18 of the pi with an RC-circuit inbetween.
GPIO18 features a hardware PWM output, which has to be set to mode 0 (non balanced, mark-space), because the balanced mode could not handle odd pwmRanges for some reason(it is badly documented).

This setup enables the atmega to read the pi's pulsed 0-3,3V output as analog input.

Pin initialization on Pi(using a python library):

    import wiringpi2 as wiringpi

    wiringpi.wiringPiSetupGpio()
    wiringpi.pinMode(18, 2)
    wiringpi.pwmSetMode(0)    #<- important part

Currently writing the Atmega side

        uint8_t  i = 0;
     uint32_t val  = 0;
     while(i<8)    //average 8 measures
     {
      i++;
      ADMUX   = 0 & 0x1f;    //select channel 0 (PA0)
      ADMUX |= (1<<5);       //set ADLAR bit ADCH > ADCL
         ADCSRA  = ADCSRA | (1 << ADSC) | (1 << ADIF);
         while (ADCSRA & (1<<ADSC));
      val = val + (ADCH);
     }
        return ((val)>>3);

Note that this reads a 10bit value on the channel and discards the least significant 2bit stored in ADCL as ADLAR is set to speed everything up.


body:
I'd like to create a process to programmatically turn-on/activate a separate USB device connected to my computer...Thinking another way to state the problem, I want the Arduino to complete the USB power circuit and then "turn off" on a schedule.

In an essence, I'd like to have my Arduino facilitate the manual process of un-plugging a USB into my computer (lets say for 5 seconds) and then re-plugging it in (let's say for 5 mins)-- rinse and repeat on a schedule....I'd like to have this coded/programmed though (I'm ok in the Arduino IDE -- sample code would really help me out a ton though) -- I'm not going to setup an actual servo to do this.

I thought getting a Arduino Shield would be the right place to start but I'm really lost.  I also thought getting a USB cable with a flip power switch might be another way to tackle the problem too-- but I haven't started to mess with it yet.

Any ideas or resources to point me in the right direction are greatly appreciated.  Thanks so much.

title: Arduino Uno (or Teensy 3.2) programmatically powering an external USB connection

Answers: 2

body:
I'm not aware of any off the shelf "shields" which would accomplish this goal.  Since you do not seem to want your Arduino device to play either the USB host or client role, but rather to interrupt power to a difference device, a traditional USB shield is probably not going to help.

Rather it would be useful to look at how the small minority of USB hubs that implement software control of downstream power on a port-by-port basis do it - USB allows for this, but doesn't require it, and most hub ICs have output pins to drive power switches, but don't include them.

Switching the 5v USB VBUS needs to be a done with a "high side switch" - a P-channel MOSFET would be an obvious candidate, but it has been historically harder to find good ones.  Some time ago I ordered a few Richtek RT9701GB USB power switch ICs - apparently they are actually more effective N-channel FET's packaged with surrounding circuitry to make them usable on the high side - but that project was shelved so they remain untried.  If you are up for creating an extremely simple surface mount board to hold them (or can find one already made) they might be worth a try.

At the crude end you could probably use a relay board. There are hubs sold with mechanical power buttons that can be very useful when debugging USB-based embedded systems as you can power cycle them without constant unplugging, and this would be a sort of automated version of that.

It's an interesting question however, if removing the power to a USB peripheral while the data lines remain connected is proper.  This is problematic in the simplest design of an ESD protected input, as the built in protection diode means that the data signal ends up trying to power the unpowered IC, something it isn't usually rated to do, but actually USB circuitry may be more complicated.  An original USB "A" connector is made with the power and ground pins longer than the data ones, in the intent that they connect first.   Pragmatically, I've seen numerous USB devices survive data connection without power - but it could be interesting to read the specs (both USB and of the data sheets of particular devices implementing it) and see what they say about this.

Another tactic could be to get one of the hubs with buttons, take it apart, and wire a relay across one of the buttons.

Or, if you did get one of the rare USB hubs that actually includes controllable downstream power switches, an investigatory dive into the depths of your computer's USB stack should theoretically yield a way to control them from software there, potentially eliminating the need for the Arduino/Teensy.

body:
    At the crude end you could probably use a relay board.

hmmm, you RAAAANNNNNGG? (yes finally a reason validating my existence!)

Sorry, but I just couldn't resist chiming in on this topic. So what I can add is:

  I have a Teensy 3.2 - RPi2 contraption at a site which is impersonating a
 USB mouse, from the security NVR's perspective (think Fred Sanford meets Frankenstien) And since I just couldn't grok using the serial UART (I think) I did everything using relays and optocouplers. So I SSH my way into the RPi's using Putty to initialize a VNC connection (just once per restart; although ugly, this sure beats the trauma of BASHing commands into RPi which elf up its bootup behavior to autostart VNC) So now instead of dreary CLI hell I have an ARM friendly release of the latest Arduino 1.6.13 IDE(emphasis on GUI !!)  which (as of like the last few months) NOW SUPPORTS Teensy 3.2 with Teensyduino! (meaning support for teensyloader as well) Pretty slick, huh? Write Arduino sketches "anywhere on earth" with full GUI support and flash  them  onto a Teensy (well at least it's impressive to me...)

OK, so now comes the crude hacking of ugly relays I salvaged dumpster diving (that's pronounced "F-R-EE") The flaw in my setup is how to get the freshly programmed Teensy to change hosts? So I built an mechanical A-B switcher (2 hosts sharing a single client). Originally I was way cautious so I used four double pole relays for pluging/unplugging in a 5 step process controlled by three of RPi's GPIOs. USB power supply lines from the Teensy feed the poles on a DPDT relay, disconnecting Teensy from all power if energized. N.C. contacts feed the poles on another relay that selects one of two hosts. The N.C. contacts on this relay feed the NVR, so that if control circuitry fails to deliver power to any given relay coil, the "normal" contacts default to Teensy being fully connected to the NVR, which normally doesn't shut down. The Rx & Tx lines were wired the same way.

When jumping from host to host, I used the rule for PA amplifiers to remember: last to power up, first to power down. The five step sequence is derived from this rule, which is: `ENERGIZE SIGNAL RELAY`, ` ENERGIZE POWER RELAY`, `TOGGLE SWITCHING RELAY`, `KILL POWER RELAY`, `KILL SIGNAL RELAY` This is the weakness in my system, because I use the same script regardless of the host. The middle step is just "toggle" and led to a sloppy protocol. Rigorous fool-proofing shouldn't allow a script to end with the A-B selector having an energized relay since the fall-back safety configuration was hard-wired for all relays being in their normal, unenergized state. As long as a relay is energized, the script keeps running would be best practice. So, being lazy and absent-minded, it wasn't long before I rebooted the RPi with the Teensy still attched. Sheer terror. And the next time, merely anxiety. Subsequent breaches of protocol became simple annoyances. So now, protocol is a joke, reboot has all the dignity associated with an episode of Jersey Shore! (translation the signal/power concern hasn't been an issue in this situation)

Bottom line, mechanical port switchers have worked great for me. After the Teensy project is complete, I plan on using it to switch a USB drive between the NVR to archive important files, and a RPi for file sharing over the web. And remember, mechanical switchs (with relays belonging to the family) are still superior to Silicon based devices in many way. For example, leakage current in mechanical switches is almost nil, they have no polarity constraints, consume no current, and produce no noise in a static state.

And finally, regarding this passage:

`Another tactic could be to get one of the hubs with buttons, take it apart, and wire a relay across one of the buttons.`

 I'd like to share a gem I unearthed on eBay: a finer link you cannot find and is as fresh as today's date. So here's a hub that I think matches your description:

http://www.ebay.com/itm/NEW-7-Port-High-Speed-USB-2-0-External-Multi-Expansion-Hub-with-ON-OFF-Switch-LO-/161831365420?hash=item25ade6ab2c

Yes, that a 7 port hub with a toggle switch and indicator led on each port. Delivered right to your door for the tidy sum of US$3.01 What kind of numbers does it benchmark at? Hmmm. you might be missing the point. It's a 7 port UBS hub with bells $ whistles with FREE SHIPPING for 3 BUCKS !!!

(CLEAR)


body:
I have an Arduino Mega and a 4-channel relay module.

This is the [relay][1] module.

  [1]: http://www.amazon.com/SainSmart-101-70-101-4-Channel-Relay-Module/dp/B0057OC5O8

When the Arduino digital output is LOW, the relay is energized.  When the Arduino output is HIGH, the relay coil is de-energized.

How can I fix this?

title: Arduino relay module working in a wrong way

Answers: 4

body: That's how they're designed to work energized is LOW de-energized is HIGH you just need to take this into account when writing your Arduino code

body:
If you read the documentation or watch/read any tutorials on the mechanical relay you are using you will learn that LOW is active and HIGH is inactive for these devices. There is no way to change that behavior, that is how they are built. (Well, you can, but it's not worth the effort)

This design is intentional to prevent relay activation on power-up or system reset. And be sure to put this code in your setup routine to ensure proper system initialization.

    digitalWrite(Relay, HIGH);
    pinMode(Relay, OUTPUT);

Where Relay is the pin variable you defined for your relay.

Just code your routine using LOW to activate the relay when necessary.

Try this tutorial [4 channel relay tutorial][1]

  [1]: http://arduinobasics.blogspot.com/2014/09/relay-module.html

body:
Yes. some boards are working in wrong way. I suggest you to build the relay board your self. [![relay board][1]][1]. Its better to plan your project according to your requirement.

  [1]: https://i.stack.imgur.com/dvqz1.png

body: You can purchase relay boards that are active high or active low or selectable, your choice. You need to read the description to determine what type it is. Here is a link for one that is selectable high or low active: "https://www.rajguruelectronics.com/Product/1730/1 channel relay board with high low level trigger.pdf" This is an example not a recommendation. These are very popular with the Arduino crowd.


body:
I am using my uno with gshield for my cnc. I would like to put laser on it. Laser have 3 wires. Red wire to power supply +, Black wire to power supply -, White wire to Arduino digital pin. I need to Connect the Arduino board ground to power supply -, but don't know how... Simple diagram (like child is using painter) would be great.

Thanks for help,
Urban

title: Arduino uno and ttl laser

Answers: 1

body: You take a wire, connect one end to the ground on the Arduino board and the other end to the ground on your power supply. Don't forget to strip the insulation. It doesn't get simpler than that.


body: I heard that using digital io pins in INPUT_PULLUP mode is much reliable and stable than in the case of using them in INPUT MODE.Then why is INPUT MODE still used...I mean **Why isn't INPUT_PULLUP mode put as default** ??

title: Arduino digital I/O pins

Answers: 1

body:
When the internal pullups are activated, a small amount of current is *sourced* by the pin's circuitry whenever the input is low.

That means that to drive the signal low, an external driver must not only sink current to discharge the capacitance of the internal and external circuitry, but it must continue doing so to dominate the attempt of the internal pullup to make the line high so that the voltage of the resistive voltage divider formed by the internal and external resistors is low enough to be an unambiguous low.

This means that the external circuit must be stronger - not normally a problem for an active device, but potentially an issue for monitoring some very high impedance external circuit.  So for example, if you wanted an external pull-down resistor, it would have to be substantially lower in value than the internal pull-up.

It also makes low power design (long life on batteries) difficult, as a system cannot take advantage of the best micropower suspend modes when any signal is being asserted *against* the direction of a pulling resistor.  With just one or two such cases you might still get reasonable life when using flashlight batteries, but not with a coin cell, something a well designed ATmega circuit can presently do.

After seeing Igor's comment, and re-reading your post, it seems maybe you are asking why the default is to have them disabled, rather than why you have the ability enable/disable them at all.  Most likely, the reason the Arduino core software has them disabled by default is because the ATmega resets that way.  As to why the ATmega resets that way, you might have to ask the design engineers, but generally it has been the norm to have an MCU reset to a state where it has the least influence on the external circuitry.  However, that is not necessarily the best - floating (undriven) inputs can potentially cause a typical CMOS input structure to consume more power than ones weakly driven to a known value.


body: It seems that the last several times I've tried to open Arduino IDE I've encountered an error that says Launch4j, "an error occurred while starting the application".  It takes some time before that happens.  I think I've seen some stuff online about this, however I've seen some mixed answers and results for how to solve that problem.  I'm using it on a Windows 7, 64 bit system.  I've tried opening it up while my Arduino was connected and it didn't work.

title: How to deal with launch4j error

Answers: 0


body: I have a custom board designed to be essentially identical to the Arduino Micro (Atmega32u4). I can burn the bootloader (Caterina) and it burns just fine, including the fade-then-slow LED signal that indicates a successful bootloader burn. However, it does not turn up under USB. What am I doing wrong?

title: Can burn bootloader but not sketches... thoroughly mystified!

Answers: 0


body:
**Sanguino** and **Microduino** core+ both uses **`ATMEGA644PA`**. I need to write a piece of code in my library where I need to check what board has been selected.
<!-- language-all: lang-cpp -->

 #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
 # define TIMER_PWM_PIN  11             // Arduino Mega
 #elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)// Sanguino or microduino
    #    define TIMER_PWM_PIN  13        //Sanguino PD5
 #elif defined(__AVR_ATtiny84__)
 # define TIMER_PWM_PIN  6
 #else
 # define TIMER_PWM_PIN  9              // Arduino Duemilanove, Diecimila, LilyPad, etc
 #endif

If I used the above code ` #elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)// Sanguino or Microduino` will be true for both Microduino and Sanguino.

Is there a way I can know which one is it?

Here is the board.txt section for Microduino core +

 ##Microduino Core+ (644pa)
 ##############################################################
 644p.name= Microduino/mCookie-Core+ (644pa)

 644p.upload.tool=avrdude
 644p.upload.protocol=arduino

 644p.bootloader.tool=avrdude
 644p.bootloader.unlock_bits=0x3F
 644p.bootloader.lock_bits=0x0F

 644p.build.board=AVR_PLUS
 644p.build.core=arduino
 644p.build.variant=plus

title: how to differentiate in code between Sangunio and Microduino core+

Answers: 0


body:
(Let's just skip the suggestions that it's the wrong idea and interrupts for a while...).

Is there a way to replace the `digitalWrite()` method (for example) so I can add something more to happen in there? But the following rules must be obeyed:

 - A call to `digitalWrite(pin, value)` must invoke the new method.
 - A call to `digitalWrite(pin, value)` from **a different library** included in my code (SD.h for example) must invoke the new method.
 - None of the Arduino files can be modified (I don't want to do it on every Arduino version upgrade).
 - Everything must be done in a header file that I can include to use the new function.

I have tried this and it works, but only in my code, not in external libraries that I include after this header:

    #include <Arduino.h>

    class PinsHook {
      public:
        static void digitalWriteHook(uint8_t pin, uint8_t value) {
          digitalWrite(pin, value);
          if (pin == 8) {
            Serial.print("Pin ");
            Serial.print(pin);
            Serial.print(" changed to ");
            Serial.println(value);
          }
        }
    };

    #define digitalWrite(pin, value) PinsHook::digitalWriteHook(pin, value)

title: Is there a way to replace an Arduino core function without modifying the Arduino code?

Answers: 7

body:
Did you try with a C macro?

    #define digitalWrite(a, b) \
    (pre(), digitalWrite(a, b), post())

this evaluates to the retval of `post()`

you can omit either the `pre()` or the `post()` functions/macros.

This needs to be placed somewhere that is included whenever the header for digitalWrite is included, so that it can override it.

The only other alternative is to become creative with the library binary.

Or, just be reasonable and modify the source code.
It's specifically available so that people can modify it.

Wrt not repeating the modification every time there is a new Arduino release, that should be avoidable.
If you build the environment from the git sources, you can maintain your patch by merging/rebasing onto the master branch.

body:
Not sure about the Arduino IDE (I don't have it installed right now) but using [UECIDE](http://uecide.org) it's as simple as defining a new `digitalWrite` function in your code.  When the whole shebang gets linked together the function in your code overrides the function in the libraries.

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

    void loop() {
        digitalWrite(13, HIGH);
        delay(100);
        digitalWrite(13, LOW);
        delay(800);
    }

    void digitalWrite(int pin, int level) {
        // Not gonna do anything!
    }

Comment out the digitalWrite function and the LED blinks.  Uncomment it and it doesn't blink any more.

body:
Arduino uses the avr compiler to compile its standard library into a `core.a` file.
Due to the [way the avr-gcc linker works](http://www.nongnu.org/avr-libc/user-manual/library.html) and the order in which Arduino specifies the link order, you're able to "override" the behavior of core functions by copying the file that contains the method you want to alter into your project.

> The compiler compiles a single high-level language file (C language,
> for example) into a single object module file. The linker (ld) can
> only work with object modules to link them together. Object modules
> are the smallest unit that the linker works with.
>
> Typically, on the linker command line, you will specify a set of
> object modules (that has been previously compiled) and then a list of
> libraries, including the Standard C Library. The linker takes the set
> of object modules that you specify on the command line and links them
> together. Afterwards there will probably be a set of "undefined
> references". A reference is essentially a function call. An undefined
> reference is a function call, with no defined function to match the
> call.
>
> The linker will then go through the libraries, in order, to match the
> undefined references with function definitions that are found in the
> libraries. If it finds the function that matches the call, the linker
> will then link in the object module in which the function is located.
> This part is important: the linker links in THE ENTIRE OBJECT MODULE
> in which the function is located. Remember, the linker knows nothing
> about the functions internal to an object module, other than symbol
> names (such as function names). The smallest unit the linker works
> with is object modules.
>
> When there are no more undefined references, the linker has linked
> everything and is done and outputs the final application.
>
> ....
>
> The linker will search libraries in the order that they appear on the
> command line. Whichever function is found first that matches the
> undefined reference, it will be linked in.

Arduino's linking occurs in this order:

 - Project Files
 - Libraries
 - core.a (Arduino std lib)

So, copying the file from the Arduino installation location (`C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino`) into your project and modifying it will result in it using your modified implementation.

This will certainly over-ride it for any files in your project, and *I believe* it will also override it in any libraries you're using as well, so be careful with this approach.

body:
<s>Just throwing an idea. No time to test now.</s>

**Edit**: I tested the solution below, and it works as expected,
provided both the `__wrap_` and `__real_digitalWrite()` are declared
`extern "C"`.

If you can convince the IDE to add extra options to the compile command
line, you could:

1. name `__wrap_digitalWrite()` your implementation of `digitalWrite()`
2. inside it, call `__real_digitalWrite()` when you want to get the
   implementation from Arduino core
3. add `-Wl,--wrap=digitalWrite` to the compile command of the final
   link step

Example wrapper:

    extern "C" {
        void __wrap_digitalWrite(uint8_t, uint8_t);
        void __real_digitalWrite(uint8_t, uint8_t);
    }

    // Calls to digitalWrite() are diverted to this.
    void __wrap_digitalWrite(uint8_t pin, uint8_t value)
    {
        __real_digitalWrite(pin, value);  // call implementation from Arduino core
        if (pin == 8) {
            Serial.print(F("Pin 8 changed to "));
            Serial.println(value);
        }
    }

Trying to put this inside a class won't help.

C.f. the [man page of gnu ld](https://linux.die.net/man/1/ld).

body:
In your code module, define your own wrapper function, and use the global scope operator to reference the Arduino function:

    void pinMode(int pin, int pinmode)
    {
      /*use my custom function?*/
      if(pin >= MY_OWN_PIN_CODES_BASE)
      {
        /*todo : my own custom pin access*/
        example_pinmode(pin, pinmode);
      }
      else /*use regular Arduino function*/
      {
        /*use global scope operator :: to call Arduino library version*/
        ::pinMode(pin, pinmode);
      }
    }

Remember, the linker has rules for which one it references.  The global scope operator forces the linker to choose the globally available one, while the custom wrapper function is seen privately by the module.

body:
"Maybe" using the c++ "functions overriding" feature can help

    void digitalWrite(uint8_t P, int8_t V, bool _wrap)
    {
      Serial.print("wrap digitalwrite");
      digitalWrite(P,V);
    }

Thus, if you call in you main application:

    digitalWrite(pin_button, 1, 0);

The wrapped version will be called

and if you used this:

    digitalWrite(pin_button, 1);

The original one will be called

----------

You may also use this definition:

    void digitalWrite(double P, int8_t V)
    {
      Serial.print("wrap digitalwrite");
      //digitalWrite(P,V); Calling it even with (int) P will cause a recursive loop
    }

But in-order to use it you need to define a variable with double type:

    double pin;
    pin = 13;
    digitalWrite(13,1);

body:
The information from Rubber Duck is correct but incomplete.

I need a huge amount of digital PWM output for hobby train control.

So I connected 4 x 74HC595 to my At Mega which must be fed with a 2 kHz bit pattern through 0,5 ms. interrupts.

My serial shift function that shifts 32 bits into the registers takes 562 us per cycle. Impossible.

I made an optimized version of digitalWrite and Read, which takes 328 us. Now it is possible to PWM with 2 kHz. The trick is that my optimized function remembers the last 2 Pins including its bitmasks and outports;  and  I skip the Timer check. It is thread safe. For a single digitalWrite this takes a tiny bit more time. With repeating writing to datapin and clockpin it improves the standard Arduino digitalWrite with about 42%.

By the way: With the digitalWriteFast library the result is 45,8 µs, a really enormous improvement. But this library handles only writes, if the pin number is known (and thus fixed!) at compile time. That is not the case with my LiquidCrystal library, where either 4 or 8 bits parallel are written to the shield via 4 sequential pins.

I got my optimized digitalWrite only working for my application including the LiquidDisplay when I copied the C:\Users\Dell\Downloads\arduino-1.8.5\hardware\arduino\avr\cores\arduino library to a subfolder in the folder of my application, called

C:\Users\Dell\Google Drive\ …\…..**\AppFolder\libraries**.

When I replaced in both folders the **wiring_digital.c** with my optimized version, it worked.

I could not get it at work, when I only replaced the wiring_digital.c in the Arduino library (the LiquidCrystal took the standard function somewhere else).

Adding only wiring_digital.c in de subfolder of my application generated a mass of linking errors.

Thus I copied the whole Arduino folder (which is not that large) to my subfolder in the application and it compiles without any problem. Not a very elegant solution, because there is a replication of the whole library; but it works.

Conclusion to override a core Arduino function:

• Put your changed function(s) (.c and/or .h) in the Arduino library, and copy this library entirely to the subfolder "libraries" in your application folder.  Then all other libraries will also use your own changed function.

Conclusion performance digitalWrite in a real 32 bit serial shift :

• An optimized  generic digitalWrite and Read easily outperforms the standard one with 42% if 2 pins are used in repetition.
• digitalWriteFast (with determined pins at compile time) outperforms the standard digitalWrite in a real 32 bit shift application with 92% (is 12,2 times faster).

Hope this helps other Arduino users…..

    //**********************
    void digitalWrite(uint8_t pin, uint8_t val)
    //**********************
    {
    uint8_t
      timer,
      bit,
      port;

    volatile uint8_t *out; // volatile because bitmask may be changed by (higher) interrupt

    uint8_t oldSREG;

    static uint8_t pin1 = 0,
                   pin2 = 0;

    static bool    p1   = true; // boolean toggle memory

    static uint8_t // Store 2 sets of port/out adresses static

    //          timer1, //now exclued. Safety threat?
              bit1,
              *out1,
    //          timer2,
              bit2,
              *out2;

      oldSREG = SREG;  // CLI for thread proof function
      cli();
      if ( (pin == pin1) || (pin == pin2) )
      {
        if (pin == pin1)   //Compiler optimizes this excellent (see ASM listing)
        {
          if (val == LOW)
          {
            *out1 &= ~bit1;
          } else
          {
            *out1 |= bit1;
          }
        }
        else
        if (pin == pin2)
        {
          if (val == LOW)
          {
            *out2 &= ~bit2;
          } else
          {
            *out2 |= bit2;
          }
        }

        SREG = oldSREG;
      }
      else  //normal clumsy digitalWrite operation
      {
        SREG = oldSREG;   //Enable interrupts again
        timer = digitalPinToTimer(pin);
        bit = digitalPinToBitMask(pin);
        port = digitalPinToPort(pin);
        if (port == NOT_A_PIN) return;

        // If the pin that support PWM output, we need to turn it off
        // before doing a digital write.
    //    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

        out = portOutputRegister(port);

        oldSREG = SREG;
        cli();

        if (val == LOW) {
          *out &= ~bit;
        } else {
          *out |= bit;
        }

        if (p1)        // Save this port, bit and out, also atomic
        {
          pin1  = pin;
          bit1  = bit;
          out1  = out;  // save the pointer, not the value
        }
        else
        {
          pin2  = pin;
          bit2  = bit;
          out2  = out;  // save the pointer, not the value
        }
        p1 = !p1;
        SREG = oldSREG; //enable interrupts
      }
    }

    //**********************
    int digitalRead(uint8_t pin)
    //**********************
    {

    uint8_t
      oldSREG,
      timer,
      bit,
      port;

    static uint8_t pin1 = 0;

    bool           readBit;

    static uint8_t // Store 2 sets of port/out adresses static

    //          timer1, //now exclued. Safety threat?
                  port1,
                  bit1;

      oldSREG = SREG;
      cli();
      if (pin == pin1)
      {
        readBit = (*portInputRegister(port1) & bit1);
        SREG = oldSREG;
        return readBit;
      }
      else
      {
        SREG = oldSREG;
        timer = digitalPinToTimer(pin);
        bit = digitalPinToBitMask(pin);
        port = digitalPinToPort(pin);

        if (port == NOT_A_PIN) return LOW;

        // If the pin that support PWM output, we need to turn it off
        // before getting a digital reading.
      //  if (timer != NOT_ON_TIMER) turnOffPWM(timer);

        oldSREG = SREG;
        cli();
        pin1 = pin;       //Atomic operation pin - bit combi must be correct
        bit1 = bit;
        port1 = port;
        SREG = oldSREG;

        if (*portInputRegister(port) & bit) return HIGH;
        return LOW;
      }
    }


body:
I have code that receives values from a serial connection, then uses those values to generate sine wave points. These sine wave points are used to position multiple servos.

I am currently trying to decrease the resolution of the sine wave points so there is more time for the servo to reach its given position.

The only way I can think of to accomplish this is by increasing the time between writing servo positions. As far as I can tell, I have implemented this correctly, however it results in a sine wave of a lower frequency.

The method I am using to alter the resolution is by changing the variable `sine_time`, which is used in the conditional statement `if(currentMillis - previousMillis >= sine_time)`, near the bottom of the program.

    /*
    This is a program that recieves sine wave parameters from a serial connection in a single string.
    The string is parsed and converted into numbers, which are plugged into 8 sine equations to generate
    positions for each joint of the robot.
    */

    #include <Servo.h>

    Servo SB, SF, HB, HF, EB, EF, KB, KF;
    int iAmp, iF_offset, iB_offset, iFk_offset, iBk_offset, pos[] = {0,1,2,3,4,5,6,7};
    unsigned int t = 0;
    unsigned long previousMillis = 0;
    float fKnee_amp, fAfreq, fPhase, fGait;

    void setup(){
      //Start serial stream at 115200 baud
      Serial.begin(115200);

      //Connect servos to Arduino
      HB.attach(2);
      KF.attach(3);
      SB.attach(4);
      EB.attach(5);
      HF.attach(6);
      KB.attach(7);
      SF.attach(8);
      EF.attach(9);

      delay(3000);
    }

    void loop(){
      char c, buffer[10];
      String readString, amp, knee_amp, afreq, gait, phase, f_offset, b_offset, fk_offset, bk_offset;
      //change the resolution of the sine wave (lower value is higher resolution)
      //digital servos refresh at a rate of 50Hz which is 0.02s
      float sine_time = 100;

      while (Serial.available() && readString.length() < 37){
        //delay to allow buffer to fill
        delayMicroseconds(10);
        if (Serial.available() > 0){
          //get one byte from serial buffer
          char c = Serial.read();
          //creates the string "readString"
          readString += c;
        }
      }

      if (readString.length() > 36){
        //see what was received
        Serial.println("The string is: " + readString);
        Serial.println(readString.length());

        //parse serial string into separate parameters
        amp = readString.substring(0, 3);
        knee_amp = readString.substring(3, 7);
        afreq = readString.substring(7, 11);
        phase = readString.substring(11, 15);
        gait = readString.substring(15, 20);
        f_offset = readString.substring(20, 24);
        b_offset = readString.substring(24, 28);
        fk_offset = readString.substring(28, 32);
        bk_offset = readString.substring(32, 36);
        /*
        //Print to serial monitor to see parsed results
        Serial.println("Hip Amp: " + amp);
        Serial.println("Knee Amp: " + knee_amp);
        Serial.println("Afreq: " + afreq);
        Serial.println("Gait: " + gait);
        Serial.println("Phase: " + phase);
        Serial.println("F Offset: " + f_offset);
        Serial.println("B Offset: " + b_offset);
        Serial.println("Fk Offset: " + fk_offset);
        Serial.println("Bk Offset: " + bk_offset + "\n");
        */
        //convert string values to numbers
        iAmp = amp.toInt();

        knee_amp.toCharArray(buffer, 10);
        fKnee_amp = atof(buffer);
        memset(buffer, 0, sizeof(buffer));

        afreq.toCharArray(buffer, 10);
        fAfreq = atof(buffer)/100;
        memset(buffer, 0, sizeof(buffer));

        phase.toCharArray(buffer, 10);
        fPhase = atof(buffer);
        memset(buffer, 0, sizeof(buffer));

        gait.toCharArray(buffer, 10);
        fGait = atof(buffer);
        memset(buffer, 0, sizeof(buffer));

        iF_offset = f_offset.toInt();
        iB_offset = b_offset.toInt();
        iFk_offset = fk_offset.toInt();
        iBk_offset = bk_offset.toInt();

        //clear strings
        readString="";
        amp="";
        knee_amp="";
        afreq="";
        gait="";
        phase="";
        f_offset="";
        b_offset="";
        fk_offset="";
        bk_offset="";
      }

      //if the joints should be oscillating
      if (fAfreq > 0){
        //determine joint positions
        pos[0] = iAmp * sin(fAfreq*t) + 1500 + iF_offset;
        pos[1] = iAmp * sin(fAfreq*t) + 1522 - iF_offset;
        pos[2] = iAmp * sin(fAfreq*t + fGait) + 1500 + iB_offset;
        pos[3] = iAmp * sin(fAfreq*t + fGait) + 1446 - iB_offset;

        pos[4] = iAmp*fKnee_amp*2 * sin(fAfreq*t + fPhase) + 1500 + iFk_offset;
        pos[5] = iAmp*fKnee_amp * sin(fAfreq*t + fPhase) + 1500 - iFk_offset;
        pos[6] = iAmp*fKnee_amp*2 * sin(fAfreq*t + fGait + fPhase) + 1500 + iBk_offset;
        pos[7] = iAmp*fKnee_amp*2 * sin(fAfreq*t + fGait + fPhase) + 1538 - iBk_offset;
        /*
        //print parameter variables
        Serial.println(iAmp);
        Serial.println(fKnee_amp);
        Serial.println(fAfreq);
        Serial.println(fGait);
        Serial.println(fPhase);
        Serial.println(iF_offset);
        Serial.println(iB_offset);
        Serial.println(iFk_offset);
        Serial.println(iBk_offset);

        //print servo positions
        Serial.println(pos[0]);
        Serial.println(pos[1]);
        Serial.println(pos[2]);
        Serial.println(pos[3]);
        Serial.println(pos[4]);
        Serial.println(pos[5]);
        Serial.println(pos[6]);
        Serial.println(pos[7]);
        */
        //get time in milliseconds
        unsigned long currentMillis = millis();

        //if the time threshold has been passed
        if(currentMillis - previousMillis >= sine_time){

          Serial.println(currentMillis - previousMillis);

          previousMillis = currentMillis;

          //write servo positions
          HB.writeMicroseconds(pos[2]);
          KF.writeMicroseconds(pos[6]);
          SB.writeMicroseconds(pos[0]);
          EB.writeMicroseconds(pos[4]);
          HF.writeMicroseconds(pos[3]);
          KB.writeMicroseconds(pos[7]);
          SF.writeMicroseconds(pos[1]);
          EF.writeMicroseconds(pos[5]);

          //increment time parameter
          t+=1;
        }
      }
    }

title: How to Change the Output Resolution of Sine Wave Controller

Answers: 1

body:
Your sine waves depend on “time” via appearances of `fAfreq*t` in lots of places.  However, `t` actually is a pass counter, rather than reflecting true elapsed time.

Instead of incrementing `t` by 1, increment it by a value that's proportional to elapsed time.  Or, more directly, set `t` equal to a multiple of elapsed time.  For example, whenever you start over, record current time via `basetime = millis()`.  Then, just after your `//determine joint positions` comment, say `t = speedratio * (millis()-basetime);`.


body:
We're using two RDM6300 RFID readers for this, and the code works when plugged into an UNO, but not when connected to the Yun. We have one of the rfids plugged into the rx pin (0 on the digital side) and the other plugged into pin 2 (same exact way we had it working on the UNO). Anyway, is there something majorly different between working with just sketches on Yun vs UNO? This code doesn't even involve using the Linux side yet as we couldn't get this major part figured out. Any help would be appreciated

    #include <SoftwareSerial.h>

        //2nd RFID using SoftwareSerial
        SoftwareSerial RFID(2, 3); // RX and TX

        // define constants for pins
        int UNLOCK = 8;

        // variables to keep state
        int readVal = 0; // individual character read from serial
        unsigned int readData[10]; // data read from serial
        int counter = -1; // counter to keep position in the buffer
        char tagId[11]; // final tag ID converted to a string

        char* authorizedTags[4]; // array to hold the list of authorized tags

        // fills the list of authorzied tags
        void initAuthorizedTags() {
          //tags
          authorizedTags[0] = "02006750B7";
          authorizedTags[1] = "02006750B1";
          authorizedTags[2] = "02006750B2";
          authorizedTags[3] = "02006750B3";
          authorizedTags[4] = "02006750B4";
        }

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

          //start serial to RFID reader2
          RFID.begin(9600);

          pinMode(UNLOCK, OUTPUT);
        //  pinMode(SUCCESS, OUTPUT);
        //  pinMode(ERROR, OUTPUT);
          initAuthorizedTags();
        }

        // check if the tag ID we just read is any of the authorized tags
        int checkTag() {
          int i;

          for (i = 0; i < 4; ++i) {
            if (strcmp(authorizedTags[i], tagId) == 0) {
              return 1;
            }
          }
          return 0;
        }

        // convert the int values read from serial to ASCII chars
        void parseTag() {
          int i;
          for (i = 0; i < 10; ++i) {
            tagId[i] = readData[i];
          }
          tagId[10] = 0;
        }

        // once a whole tag is read, process it
        void processTag() {
          // convert id to a string
          parseTag();

          // print it
          printTag();

          // check if the tag is authorized
          if (checkTag() == 1) {
            tagSuccess(); // unlock solenoid
          } else {
            tagFailed();
          }
        }

        void printTag() {
          Serial.print("Tag value: ");
          Serial.println(tagId);
        }

        // perform an action when an authorized tag was read
        void tagSuccess() {
          Serial.println("Tag authorized.");

          //activate solenoid,
          digitalWrite(8, HIGH);
          delay(3000);
          digitalWrite(8, LOW);
        }

        // inform the user that the tag is not authorized
        void tagFailed() {
          Serial.println("Unauthorized access!");

        }

        // this function clears the rest of data on the serial, to prevent multiple scans
        void clearSerial() {
          while (Serial.read() >= 0) {
            ; // do nothing
          }
        }

        void loop() {

        //RFID 1
          if (Serial.available() > 0) {

            // read the incoming byte:
            readVal = Serial.read();

            // a "2" signals the beginning of a tag
            if (readVal == 2) {
              counter = 0; // start reading
            }
            // a "3" signals the end of a tag
            else if (readVal == 3) {
              // process the tag we just read
              processTag();

              // clear serial to prevent multiple reads
              clearSerial();

              // reset reading state
              counter = -1;
            }
            // if we are in the middle of reading a tag
            else if (counter >= 0) {
              // save valuee
              readData[counter] = readVal;

              // increment counter
              ++counter;
            }
          }

        if (RFID.available() > 0)
        {
            // read the incoming byte:
            readVal = RFID.read();

            // a "2" signals the beginning of a tag
            if (readVal == 2) {
              counter = 0; // start reading
            }
            // a "3" signals the end of a tag
            else if (readVal == 3) {
              // process the tag we just read
              processTag();

              // clear serial to prevent multiple reads
              clearSerial();

              // reset reading state
              counter = -1;
            }
            // if we are in the middle of reading a tag
            else if (counter >= 0) {
              // save valuee
              readData[counter] = readVal;

              // increment counter
              ++counter;
            }
        }

        }

title: RFID Code (and setup) works on an UNO but not on the Yun

Answers: 0


body:
I have an Arduino Uno with an RS-232 shield, and a servo drive that communicates via CAN or RS-232. I'm trying to communicate with this drive using an RS-232 cable, but I'm getting no response. I'm using the SoftwareSerial library on the Arduino to use digital pins 3 and 2 as rx and tx. Only pins 2 (RxD), 3 (TxD), and 5 (GND) of RS-232 are used to communicate with the drive. 19,200 is the default baud rate for the drive. The drive is powered with a dedicated power supply. The drive is supposed to echo every character received back to the sender.

I've had success using a simple Java program to communicate with the drive using the same kind of cable (although with a USB-to-serial converter). The drive echos all characters back, and the motor responds to the commands sent to the drive. The cable used has a female DB9 connector on one end (to communicate with the desktop) and a custom 3 pin connector on the other (to communicate with the drive).

I've also had success with the same Java program communicating with the Arduino (also with the converter). This cable has a female DB9 connector on one end (to communicate with the desktop) and a male DB9 connector on the other (to communicate with the Arduino).

But I've had no success exchanging data between the Arduino and the drive. There is no response back from the drive nor does the motor respond to any commands. The cable used for this has a male DB9 connector on one end (to communicate with the Arduino) and a custom 3 pin connector on the other (to communicate with the drive).

Each cable has been tested with a voltmeter to confirm that pins on one end are connected to the correct pins on the other end.

I'm at a loss here. Is there something I'm missing?

For your consideration, here is the Arduino code. It is the same whether it is connected to the desktop or the drive.

    #include <SoftwareSerial.h>
    #include <SPI.h>

    const int rx = 3;    // software serial receive pin
    const int tx = 2;    // software serial transmit pin
    const int baudRate = 19200;  // 19,200 bits per second for read and write serial functions

    SoftwareSerial serial(rx, tx);

    /*
     * Initial, one-time setup
     */
    void setup()
    {
     Serial.begin(baudRate);  // open hardware serial communications
     serial.begin(baudRate);  // open software serial communications

     serial.println("MO=1;");      // start motor
     serial.println("JV=30000;");  // set velocity to 30,000 counts/second
     serial.println("BG;");        // begin movement
    }

    /*
     * Executes every tick
     */
    void loop()
    {
     if (serial.available())
     {
      Serial.write(serial.read());
     }

     if (Serial.available())
     {
      serial.write(Serial.read());
     }
    }

Also, here is the Java code.

    import gnu.io.CommPort;
    import gnu.io.CommPortIdentifier;
    import gnu.io.SerialPort;

    import java.io.FileDescriptor;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;

    public class TwoWaySerialComm
    {
        public TwoWaySerialComm()
        {
            super();
        }

        void connect(String portName) throws Exception
        {
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
            if (portIdentifier.isCurrentlyOwned())
            {
                System.out.println("Error: Port is currently in use");
            }
            else
            {
                CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);

                if (commPort instanceof SerialPort)
                {
                    SerialPort serialPort = (SerialPort)commPort;
                    serialPort.setSerialPortParams(19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

                    InputStream in = serialPort.getInputStream();
                    OutputStream out = serialPort.getOutputStream();

                    (new Thread(new SerialReader(in))).start();
                    (new Thread(new SerialWriter(out))).start();

                }
                else
                {
                    System.out.println("Error: Only serial ports are handled by this example.");
                }
            }
        }

        /** */
        public static class SerialReader implements Runnable
        {
            InputStream in;

            public SerialReader(InputStream in)
            {
                this.in = in;
            }

            public void run()
            {
                byte[] buffer = new byte[1024];
                int len = -1;
                try
                {
                    while ((len = this.in.read(buffer)) > -1)
                    {
                        System.out.print(new String(buffer, 0, len));
                    }
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }

        /** */
        public static class SerialWriter implements Runnable
        {
            OutputStream out;

            public SerialWriter(OutputStream out)
            {
                this.out = out;
            }

            public void run()
            {
                try
                {
                    int c = 0;
                    while ((c = System.in.read()) > -1)
                    {
                     //System.out.print(c);
                        this.out.write(c);
                    }
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }

        public static void main(String[] args)
        {
            try
            {
                (new TwoWaySerialComm()).connect("COM4");  // COM4 is port of USB-to-serial converter
            }
            catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

title: No response from device when trying to communicate with it via RS-232

Answers: 1

body: I've found the issue. The serial cable I was using was too long, introducing resistance to the signal. That's it!


body:
I am getting no response back from an ESP8266 WIFI with Arduino Mega using library ITEADLIB_Arduino_WeeESP8266.

    //serial monitor response

    setup begin

    FW Version:

    to station + softap ok

    Join AP success

    IP:

    single ok

    setup end

    create tcp ok

    release tcp ok

    create tcp ok

**Arduino Mega Code**

    #include "ESP8266.h"
    #include <SoftwareSerial.h>

    #define SSID        "atmel"
    #define PASSWORD    "bets12345"
    #define HOST_NAME   "www.google.com"
    #define HOST_PORT   (80)

    SoftwareSerial mySerial(10, 11); /* RX:D3, TX:D2 */ ESP8266 wifi(mySerial);

    void setup(void) {
      Serial.begin(9600);
      Serial.print("setup begin\r\n");
      Serial.print("FW Version:");
      Serial.println(wifi.getVersion().c_str());
      if (wifi.setOprToStationSoftAP()) {
        Serial.print("to station + softap ok\r\n");
      } else {
        Serial.print("to station + softap err\r\n");
      }
      if (wifi.joinAP(SSID, PASSWORD)) {
        Serial.print("Join AP success\r\n");
        Serial.print("IP:");
        Serial.println( wifi.getLocalIP().c_str());
      } else {
        Serial.print("Join AP failure\r\n");
      }
      if (wifi.disableMUX()) {
        Serial.print("single ok\r\n");
      } else {
        Serial.print("single err\r\n");
      }
      Serial.print("setup end\r\n");
    }

    void loop(void) {
      uint8_t buffer[128] = {0};
      if (wifi.createTCP(HOST_NAME, HOST_PORT)) {
        Serial.print("create tcp ok\r\n");
      } else {
        Serial.print("create tcp err\r\n");
      }
      char *hello = "Hello, this is client!";
      wifi.send((const uint8_t*)hello, strlen(hello));
      uint32_t len = wifi.recv(buffer, sizeof(buffer), 10000);
      if (len > 0) {
        Serial.print("Received:[");
        for(uint32_t i = 0; i < len; i++) {
          Serial.print((char)buffer[i]);
        }
        Serial.print("]\r\n");
      }
      if (wifi.releaseTCP()) {
        Serial.print("release tcp ok\r\n");
      } else {
        Serial.print("release tcp err\r\n");
      }
      delay(5000);
    }

title: No Response from ESP8266 WIFI

Answers: 3

body:
Have you remembered to logic shift the ESP8266 from 3.3v to 5v?

Any by no response, do you mean no response from your web server or the board itself?

body:
If you are using an ESP-01 board (which is an ESP8266 based board)
You should try running the ESP8266 from an independent 3.3V power supply.

The Arduino Mega 3.3V pin only supplies up to 50mA, wheres as the ESP8266 requires up to 200mA.

Also, make sure the CH_PD and RESET pins are held high (connected to the 3.3V).

Because you're using an Arduino Mega, you might find it beneficial to use pins 16 and 17, and Serial2 instead of software serial.
Internet sources indicate that they are sometimes set up with a baud rate of either 9600, 57600 or 115200. I managed to get mine working with 115200, but software serial is limited to a baud rate of 19200.

body: Rx and Tx properly crossed - SwSerial Rx to ESP Tx and SwSerial Tx to ESP Rx? And the connections are sound? It wouldn't be the first time "someone" thought he'd killed an ESP, only to find a missing connection from its transmitter (not that I'd know anything about that ..... ;)


body:
I have four APA102 LED matrices (those flexible ones) and I want to connect them together to make a display for showing images. Now my problem is this:

Consider the coordinate system with four quadrants. I put one matrix in each of the quadrant and my target is to have a one single display as mentioned above. I connect like this: The input of matrix 1 is connected to Arduino, the output of matrix 1 to input of matrix 2, output of matrix 2 to input of matrix 3 (or can be input of 4 also ) and then finally output of 3 (or output of 4th matrix) is connected to input of 4th matrix (or input of 3rd matrix accordingly).

The problem with this is that although this might seem a big display from a distance with 4 matrices working in sync but actually its 4 matrices daisy chained and split into 2 rows. This would split my image if I were to display.

Question: Is it possible to parallel chain these APA102 matrices and thereby form one continuous display which can be controlled by FASTLED library?? I might be somehow able to address an individual LED in this type of weird pattern, but while displaying images, I am lost. Can't figure out how to do that? Realised that I need to have parallel chaining.....which I have no idea of.

Any help, guidance would be great!

Thanks

title: Parallel Chaining of APA102 LED matrices

Answers: 0