Common/standard library and/or protocol for Arduino to be I2C slave for driving NeoPixel I would like to control a string of WS2812/NeoPixels from a SBC like a BeagleBone or C.H.I.P. I realize someone has gone through the trouble to come up with a way to drive the WS2812 string from a BeagleBone directly with the PMU, but I would like to have an Arduino like a Pro Mini do the signal generation, while the SBC would direct the Arduino what to display.

I found the node-pixel setup with I2C backpack on the arduino, but it requires on the SBC side NodeJS, Johnny-Five and other libraries that I would have no other use for. It seems overkill.

Is there some commonly used protocol over I2C for controlling NeoPixels (with the arduino being the I2C slave), or will I be better off developing my own simple protocol?

On the SBC side, I would likely be coding either in C/C++ or Python.

You should break your project up into smaller parts.

Consider using other led strips, that can be driven directly. Consider using ready-made parts or opensource code (google).
Make an Arduino drive a NeoPixel Ledstrip. (Check adafruit libraries/NeoPixel guide)(Sanity/wiring check)
Communicate with Arduino and Beaglebone over I2C. Try sending "Hi" and respond "Ok".
Think of a protocol, how to indicate start/stop of a message.
Send the "color bytes" using said protocol.
Unpack the color bytes and put them in a pixel array (See NeoPixel library).
Run "ledstrip.show();”

Please atleast try to do these steps. If one fails, you can create a question with details on what you have tried or what isn't working.

Maybe "nodepixel" already has the Arduino code for you. You then only need to know what bytes to send over I2C, which you can do with any programming language that supports I2C access on your platform.


Connecting Arduino to PC through Slimline SATA instead of USB? I removed the DVD-RW from my laptop and want to use the new area as an IO port instead. There is an Arduino Nano with me which can fit into the emptied out drive space and there are some easy to connect IO headers with me.

The only (major) problem is how can i connect the Arduino to the slimline SATA port of the DVD drive. There are some SATA to USB converters available in the market, but will they work? (as i am trying to connect it the other way around)

Is there any possible way to connect the Arduino to the SATA port, and even if i would be able to connect it, would i be able to use it as a regular Arduino as if it were connected to a USB port?

No, there is no way of connecting an Arduino to a SATA port. You require USB or UART. SATA is a specific dedicated port, whereas USB is, as the name suggests, Universal. So USB can become SATA but SATA can never become USB.


Leonardo keypresses not working with OBS I am using an Arduino Leonardo to have hotkeys for OBS but they don't work when the OBS Studio window is not focused.
I have the Leonardo press Ctrl + Alt + Shift + F7 when I press a button connected to the Leonardo. On OBS I have Ctrl + Alt + Shift + F7 switch to a slide. When I have the OBS window focused and I press the button it works fine. But when I have another application focused it does not work. The strange thing is, is that when I press (on my keyboard) Ctrl + Alt + Shift + F7, it will switch to the slide, but when I press the button it does not work.
I am running OBS as an Administrator btw.
My code for the Leonardo is below
int pinA = 8;

void setup() {
    pinMode(pinA, INPUT);
}

void loop(){
digitalWrite(pinA, HIGH);
readPinA = digitalRead(pinA);
if (readPinA == 0){
    Serial.print("A\n");
    Keyboard.press(KEY_RIGHT_CTRL);
    Keyboard.press(KEY_RIGHT_ALT);
    Keyboard.press(KEY_RIGHT_SHIFT);
    Keyboard.press(KEY_F7);
    Keyboard.releaseAll();
    delay(250);
    }
}

Warning: the below is all supposition.
When the OBS window is focused the OS can send keyboard events to the window. That means that it gets "The button has been pressed" messages. These are generated when the "press" events are sent from the Leonardo.
When the OBS window isn't focused it can't be sent those messages - so it has to manually poll the state of the keyboard to see what buttons are pressed at any one time. It can't be doing this all the time, so it does it periodically (but still pretty fast).
The knock-on effect is, though, that when not focused it can only see buttons that have been pressed for at least enough time for it to poll the state.
If you add a delay into your routine between the last "press" and the "release all" commands that is longer than the period between polling (no idea what that is - you'll have to experiment, but starting at around 50ms to 100ms should be adequate) you should give OBS enough time to see that the buttons are pressed before you then release them.


Is it possible for the Arduino's digital pin mode to flip from OUTPUT to INPUT unexpectedly? I have an Arduino project (data logger intended to sample 100 samples per second for months) with firmware that is too long to post. It mostly works as supposed to, but I have a confusing issue I can't figure out: rarely, the indicator LEDs (driven by digital pins) stop working. By rarely, I mean if I run 20 devices for two weeks, maybe one will develop the issue, so it's very hard to test empirically but it's frequent enough that it matters. I know it's not a hardware problem because they start again after a reset. The device apparently continues working fine apart from the LED issue when this happens.
I have three hypotheses:

There's a logic problem in my firmware code. I'm skeptical because the relevant block of code is pretty simple.
A memory overflow or some similar problem causes the program to fail at this one particular task but not others. I'm a little skeptical because the device reports free stack in the metadata every second and it's always over 40 bytes; I may be misunderstanding memory use though.
Somehow, the digital pin (4) driving the LED gets flipped from OUTPUT to INPUT. There's definitely no pinMode(4, INPUT) command anywhere in my code though, so if this is happening it's not my code doing it.

Let's suppose it isn't #1. Considering #2: is it likely that a weird memory issue is causing a very specific failure while not affecting core functions of the device?
Considering #3, is there anyway the register setting a pin to INPUT or OUTPUT could be flipped unexpectedly? It sounds crazy to me but I want to rule it out.
The platform is similar to the Arduino Pro (3.3V, 8 MHz, ATMEGA328p) and I'm running the current IDE version (1.8.13). Thanks for any help.

The fact that it is possible to set them incorrectly is why, in some projects where I'm concerned about this, I'll add a small series resistance to an inbound signal.  Should the pin become OUTPUT and driven in an opposing direction to the signal, the resistance serves to prevent a short through both devices.  The possibility is always there, whether you have an outright bug, or instability, or flash corruption.
With pinMode the opportunity to accidentally set your port to the wrong direction is maybe a bit worse than for code that directly manipulates the data direction register.  pinMode calls typically don't get inlined, because pinMode on the Arduino is a fairly complicated function at runtime for what it actually does.  So, there's this generic code that can be jumped to that will set various ports to either direction, as opposed to smaller chunks of code that contain instructions that set specific ports to specific settings.
INPUT roughly takes your digital pin out of the circuit.  And INPUT_PULLUP sort of does that, with the exception that internal to the AVR there's going to be 20k - 50k of resistance going to "5V".  Knowing that, you can test your hypothesis three.  When you find your project in the state where the LED isn't lit, take some some resistance (say 1K) and use it to pull the pin toward "5V".  Then pull it to GND.  Watch the voltage at the pin with a meter.  Based on what you have attached and what you see for a voltage, you can determine whether it has entered the INPUT or INPUT_PULLUP state.  You'll also be able to see if it's just being driven to whatever state you're calling "not working" ("off" I'm guessing).
You can take all the guess work out of what voltages to see in each scenario if you upload a sketch that sets the pin in question to the INPUT, INPUT_PULLUP, OUTPUT/HIGH, and OUTPUT/LOW states and measure the voltage at the pin when you pull it to each rail with your resistor.  Later you can consult the table you've built to see what has happened.
There's only so much to say about this, particularly your first two ideas, without seeing the code and other details.  Just that sometimes otherwise simple code has bugs in it.  In an ATMega328P project, 40 bytes is not a lot of free space at all.  To give you an idea what sort of problem this can trigger: The Arduino implementation of new that's in the 1.8.3 core will happily blow away your register file and whatever else it can get to after that, if the underlying malloc reports not enough memory.  Basically new continues to initialize the object it thinks was allocated even when the pointed returned is nullptr.  The __malloc_margin is 128 in the 1.8.3.  So if you try to malloc with 40 bytes distance between the stack and heap, you will trash your program state, perhaps even setting a data direction register in the process.


How to implement Arduino NANO as a RS-232 to USB adapter (Or do I need a Arduino Mega?) For 3D printer comms I have a PC upstairs running my 3D printing slicer program (Simplify 3D). In the basement, I have several USB-enable 3D printers. My PC upstairs has a USB-to-RS-232 serial adapter. The serial side of that USB-to-Serial adapter connects to the Serial port of a Moxa Nport 6150 RS232-to-Ethernet protocol adapter. I get those Moxa devices for free when they break at work and then fix them for a couple of dollars.
The other side of the Moxa connects to my home computer network router. In the basement I can plug another Moxa into an ethernet cable on my home network and the serial RS232 output I need to connect to the Micro-USB jack of the 3D printer. How can I use an Arduino Nano (or Uno or Mega if required) to convert the RS232 data to the USB input of my 3D printer?
So I have PC->(RS-232)->[MOXA(RS-232)->Moxa(Ethernet)]->Router->[Moxa(Ethernet)->Moxa(RS-232)]->[Arduino(RS-232)->Arduino(USB)]->3D Printer(USB)... How can I get the Arduino to do that function? Items within [ and ] brackets are single devices performing a protocol conversion.
I know people use Raspberry Pi's and a program called OctoPrint to remotely control their 3D printers but I get the Moxas for free and Uno's or Nanos are dirt cheap. RPi's are more expensive and for several 3D printers it can start adding up. Any ideas?

Its not as easy as you think. An Arduino will not be enough for connecting the USB of the 3D printer. The USB protocol is strictly divided into slaves and masters. A USB(us) has exactly one master, which totally controls, what the slave can do. The slave itself cannot do much of its own.
Your 3D printer is a USB slave device. That enables a USB master (like a computer) to control it. The Arduino is also a USB slave device. If you connect both, you have a USB connection without a master. Nothing will happen. So you need to implement a USB master on the Arduino, which can handle the UART communication; all in software. That is generally possible, but I wouldn't recommend it. Also you definitely need extra hardware, because D+ and D- on USB are also electrically totally different from the TTL lines RX and TX (and also from the RS232 lines). They work differentially. So you need extra hardware to do that.
The easiest way with an Arduino would be to buy a USB host shield. With that you may be able to build, what you want.
But I would dispute, if this really makes sense. The cheapest USB host shield for Arduino, that I could find at amazon is around 10€, plus the price for an Arduino and the hassle of getting it all to work. A RaspberryPi Zero W only costs 10€. If you don't want to use wifi, you can add a USB to Ethernet adapter. And depending on the used software and its installation you might even be able to handle multiple printers with only one Pi (I use the Repertier Server, which has the ability to control multiple printers, I think). (Though depending on the number of printers and the resulting load you might wanna step up the game to a full Pi4)

There might be an additional way, depending on your printers. The printers microcontroller board might break the TX and RX pins out for you. Then you could connect the Arduino to them, no need for USB in that case. But that might not be an option. If the used microcontroller has a direct USB interface, there are no RX and TX pins to break out.


I2C Wire.write function doesn't seem to work Using the simplest code possible to test the library:

#include <Wire.h>

void setup()
{

  Wire.begin(); // join i2c bus

  Wire.beginTransmission(44); // transmit to device #44 (0x2c)
                              // device address is specified in datasheet

  Wire.write(0xA);             // sends value byte
  Wire.write(0xA);             // sends value byte
  Wire.write(0xA);             // sends value byte

  Wire.endTransmission();     // stop transmitting
}

But my data (three test byte of 0xA) is not getting sent. See image. As you can see, I get start bit, address, and then the stop bit. No data. Where am I going wrong?

According to the captured communication NACK was received (confirmed in comments) and according to the Wire library twi_stop will be called (and sent) in this fault scenario.

case TW_MT_SLA_NACK:  // address sent, nack received
  twi_error = TW_MT_SLA_NACK;
  twi_stop();
  break;


What is the best transmitter/receiver to use with an Arduino RC? I want to customize an RC car that I have because the controller is gone. I'm going to use an Arduino with a custom motor controller but I have no idea what to use for the transmitter/receiver. I've seen some IR sensors being used but I want something that uses a frequency channel. Has anyone had experience doing this? What is the easiest way to go about accomplishing a remote controlled Arduino car?

That depends largely what is controlling it

Some options include:

wifi, if you have an expansion board, from a PC or phone (spec says: 66ft/20m)
bluetooth works great, directly from your phone (spec says: 32ft/10m - 320ft/100m)
433mhz ASK transmitter/receiver from another Arduino or other hand-designed circuit (spec says: 100m/320ft)
Infrared receiver - from a TV remote! (range unknown, depends on remote & conditions; would not trust it 10m outside without testing).
Cellphone network - longest range (nationwide!). If you get a cheap android to do some of the work, you can use the phone's compass & gps & extra processing power, as well as the camera(s)!
Remote control. I know you said you lost yours, but in case someone else is looking here, you can hook up an rc receiver to an Arduino fairly easily. https://www.sparkfun.com/tutorials/348 for more info.

Many of these ranges specified will depend on the antenna. If your car can tell it's lost signal, then it can stop; otherwise you have to outrun it, or wait for it to hit a wall.

Edited to include cellphone network, and added ranges to options


How to use a Bi-color matrix led 8x8 with 24 pins? I've just buy this 8x8 LED matrix WLG M20088A/BEG and I'm trying to light all the LEDs in one single color (green) but I don't understand how the 24 pins work for this specific model.

I know that every manufacturer makes different models. Does anyone have any experience with this particular model?

Take a closer look at the device schematic diagram, which I copy below. It will tell you how each of the LEDs are wired. For example, the green LED on the upper-left corner (which I marked with a green circle) has its anode (positive terminal) wired to pin 5, while its cathode (negative terminal) is wired to pin 1. Can you see that?

To light up that LED (green LED on the upper-left corner), you must apply voltage (with limited current), to pins 1 (-) and 5 (+). If you wanted to light up the red LED at the same position instead, you should apply voltage to pins 1 (-) and 20 (+).

To light up all LEDs of a given color, you'll have to connect pins 1, 2, 3, 4, 21, 22, 23 and 24 to the negative terminal of your power supply. These are the LED common anodes. They are called common because they are shared among each pair of red and green LEDs. If you choose to use the red LEDs, you'll also have to wire pins 13 through 20 to your positive supply. On the other hand, if you pick green, you'll wire pins 5 through 12. These are the LED cathodes.

Don't forget to wire a current limiting resistor in series with each LED.


What is the proper wiring for relay module? I want to know the recommended wiring for relay. I am setting it up as NO.

Where should I connect the relay, the hot wire or the ground wire?
Where should I connect the wire going to bulb, NO or C pins of relay? Where should I connect the wire going to AC, NO or C?

A relay is a simple switch controlled by an electromagnet coil. The "NO" (normally open) side is off until you apply power to the coil. The "NC" (Normally closed) side is on until you supply power to the coil, at which point it turns off. Switches don't have polarity. If you connect the common into one part of a circuit and the "NO" side into the other, it doesn't matter which goes where.
Edit:
As another poster pointed out, you should wire the relay so it switches the hot leg from the plug, not the neutral (Assuming you're in the US or another country with polarized plugs.) That is much safer, since it means when the relay is off, the lamp is only connected to the neutral line. If, instead, you wire the relay to switch the neutral leg then the lamp will ALWAYS be connected to hot, and if somebody touches the wires they could get a shock.
Important:
What does matter is how you power the relay. If you try to drive a simple relay directly from a logic pin, it will likely damage or destroy the Arduino.
If you're using a "digital" relay that takes a constant 5V source, and a logic level control, such relays have built in transistors and protection diodes that prevent the relay coil from destroying solid state electronics.
If you're using a simple relay, you'll need an appropriate transistor to boost the current to the coil, as well as a "flyback diode" to protect the transistor from back-EMF when the coil is disconnected.


Trying to read different gas levels with MQ2 Gas Sensor I found a link on how to connect MQ-2 Gas Sensor to Arduino Uno.
http://electronicsprojectshub.com/how-to-connect-mq2-gas-sensor-to-arduino/
After I bought all the parts and tried it out, the sensor gave me this in the serial monitor

Ro: 10.81 kohm
LPG:0.00ppm    CO:0.00ppm    SMOKE:0.00ppm
LPG:0.00ppm    CO:0.00ppm    SMOKE:0.00ppm

and so on.
Here is the code I used
#include <MQ2.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16,2);
int Analog_Input = A0;
int lpg, co, smoke;
MQ2 mq2(Analog_Input);

void setup(){
  pinMode(A0, INPUT);
  Serial.begin(9600);
  lcd.begin();
  lcd.backlight();
  mq2.begin();
}

void loop(){
  float* values= mq2.read(true);
  //lpg = values[0];
  lpg = mq2.readLPG();
  //co = values[1];
  co = mq2.readCO();
  //smoke = values[2];
  smoke = mq2.readSmoke();

  lcd.setCursor(0,0);
  lcd.print("LPG:");
  lcd.print(lpg);
  lcd.print(" CO:");
  lcd.print(co);
  lcd.setCursor(0,1);
  lcd.print("SMOKE:");
  lcd.print(smoke);
  lcd.print(" PPM");
  delay(1000);
}

Please help me fix it so that it can perform just the same as the video. Thanks.

First this should be like this:

float* values= mq2.read(false); //false

and then write this to be printed in the serial monitor

Serial.print('\n');
  Serial.print("LPG:");
  Serial.print(lpg);
  Serial.print(" CO:");
  Serial.print(co);

  Serial.print('\n');
  Serial.print("SMOKE:");
  Serial.print(smoke);
  Serial.print(" PPM");
  Serial.print('\n');


Can't sync with programmer Arduino Uno I have a weird problem, and it's probably because I'm doing something wrong. I'm quite new to Arduino.
My Uno R3 (Elegoo) has been working fine for a month. It has been sitting on a bench for the past week, unused though. Last night I tried to push a sketch from the IDE: v1.8.14 on Windows 10 Pro (fully updated), board: Arduino Uno, Com port 5. I got this error:
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe6

So, I googled it and tried to fix it. No luck. And, the code changes frequently (right now it's 0x3a). So, I tried

Using the blink sketch
Rebooting my laptop
Using a different USB port
Using a different USB cable
Using different settings in the IDE (Mega 2560 with the ATMega2560 processor)
Using a different operating system (Ubuntu) on a different laptop with a different version of the IDE (1.8.13)
Using a different Arduino (A Freenove Uno r3 from a robot kit)

Using a different board on windows does work! So, my original board is bricked maybe?
I got the same result, more or less. The only difference was that the response code changed. On Ubuntu, the response code is always 0x00 so I suspect the changing code is down to some problem in windows (I trust Linux a lot more than windows). I used the default blink sketch for all these attempts.
Note: I do have a green 'on' led and the L is orange and does the 3xflash on powerup and reset. This is the only USB port in use, so there's only one to choose in the IDE (happens to be com5) and it's clearly shown as Arduino. When I push the sketch, the orange L led stays solid orange and there is no flashing of the rx or tx leds.
Update:
I have read, with interest:
Have I bricked my Arduino Uno? Problems with uploading to board
Because of this I have now checked the power rail with a multimeter and found 5v and 3.3v respectively on USB, and with a 9v battery I have 3.3v and 7.8v respectively. The L led flashes 3 times as expected on power up and reset.
Also, I have nothing attached to the board at all.
When I tried the loopback test the board would not power-on with reset connected to ground, so I don't know how to proceed with that.
I have just tried the Atmega16U2 chip test, and it failed. I'm pretty sure the wiring is correct (though it's hard to tell -- I can't find a dot indicating pin 1 on the good board so I'm guessing it's close to the 'n' in 'on' as mentioned in the post).
How could I have damaged this? What could I have possibly done to break that? I was only driving leds.

Sometimes boards can glitch depending on wear and tear or on how well they have been manufactured. Personally I always buy boards direct from the Arduino store and  I have never had this issue. One thing that could help is placing a 0.1 uF capacitor between the +5V pin and ground and another between AVcc and ground. There will be some on the PCB already but this can help in some cases. Another thing that can help is pressing the reset buttom just after pressing upload on your PC.
Unfortunately, when out of sync errors occur it can be heavily luck based as to what works and how long it takes. Hopefully one of these tricks will work! But like you say, if other boards are working fine then it could just be bricked


Error passing a `time_t` and `struct tm`, ESP32 I need to create a converter from epoch time stored in a time_t variable, to a struct tm variable, in order to check / create a certain task every hour or a day. This function should get also a past time_t for other uses.

Converting function, inside a library, works OK ( last two lines are for verification purposes, meaning conversion was done as expected ):

void myIOT32::convEpoch(time_t in_time, struct tm *convTime)
{
  convTime = gmtime(&in_time);
  char time_char[40];
  sprintf(time_char, "%04d-%02d-%02d %02d:%02d:%02d", convTime->tm_year + 1900, convTime->tm_mon+1, convTime->tm_mday,
            convTime->tm_hour, convTime->tm_min, convTime->tm_sec);

  Serial.print(" from funct: ");
  Serial.println(time_char);

Now, when calling it from my code and try to use time tm var, it causes the code to crash. In code below, I just try to print it to console:

void sendnewNotif()
{
  struct tm *newtime;
  time_t t=182423032;
  iot.convEpoch(t, newtime); // <--- Using the conversion
  char timeStamp[50];
  // Serial.print(newtime->tm_year);

}

What may be the problem ?

Guy

void myIOT32::convEpoch(time_t in_time, struct tm *convTime)
{
  convTime = gmtime(&in_time);

Here you are overwriting the parameter convTime. There is no point in
passing such a parameter if you are not going to use the value provided.

void sendnewNotif()
{
  struct tm *newtime;
  time_t t=182423032;
  iot.convEpoch(t, newtime); // <--- Using the conversion

newtime is initially uninitialized. The call to iot.convEpoch()
doesn't change that (the parameter is passed by value, not by
reference).

  Serial.print(newtime->tm_year);

This is dereferencing an uninitialized pointer, which is undefined
behavior and can crash the program.

The simplest solution I see is to have myIOT32::convEpoch() return the
pointer it got from gmtime(). Note that this points to static storage,
which makes the method not reentrant.

Example (not tested):

struct tm *myIOT32::convEpoch(time_t in_time)
{
  struct tm *convTime = gmtime(&in_time);
  // ...
  return convTime;
}

void sendnewNotif()
{
  time_t t = 182423032;
  struct tm *newtime = iot.convEpoch(t);
  Serial.print(newtime->tm_year);
}


Powering LCD Displays without a Breadboard I hope that this is not a silly question. I may be hoplelessly optimistic in asking, but is there any way to power & display information onto a LCD Display from an Arduino Uno.... Without the breadboard? I am working on a hardware project that has very strict space constraints, and the breadboard is simply not an option.

I presume you're looking at this page - the breadboard is merely a convenience, you can just hard-wire the LCD directly - most don't even come with that header plug soldered on.


problem data I2C to sensor GY955/BNO055 (China) I want to ask, I have a problem when running the Arduino sensor, I can't output data, but it's detecting that the sensor address has been paired.
Like I2C has a problem or locks it.

Last night it worked only because my twin sensors tried another with the same program after I compiled and uploaded, I see the serial monitor is only a detection sensor, but it doesn't display data, so the pitch evaporates and the roll data is 0.0,0.

There seems to be a problem with i2c: the data does not come out, it only detects the sensor address but the contents are all zero. Have you ever experienced this?

This initially worked, because the sensor was the same and I tried it with the same program after reading GY 955 / BNO055 on Euler_streaming it only showed zero per axis.

This is code in the bread board

/****************************************************************************

    Euler_Streaming.pde - part of sample SW for using BNO055 with Arduino

   (C) All rights reserved by ROBERT BOSCH GMBH

   Copyright (C) 2014 Bosch Sensortec GmbH

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

 **************************************************************************/
/*  Date: 2014/01/07
     Revision: 1.2

*/
#include "BNO055_support.h"     //Contains the bridge code between the API and Arduino
#include <Wire.h>

//The device address is set to BNO055_I2C_ADDR2 in this example. You can change this in the BNO055.h file in the code segment shown below.
// /* bno055 I2C Address */
// #define BNO055_I2C_ADDR1                0x28
// #define BNO055_I2C_ADDR2                0x29
// #define BNO055_I2C_ADDR                 BNO055_I2C_ADDR2

//Pin assignments as tested on the Arduino Due.
//Vdd,Vddio : 3.3V
//GND : GND
//SDA/SCL : SDA/SCL
//PSO/PS1 : GND/GND (I2C mode)

//This structure contains the details of the BNO055 device that is connected. (Updated after initialization)
struct bno055_t myBNO;
struct bno055_euler myEulerData; //Structure to hold the Euler data

unsigned long lastTime = 0;

void setup() //This code is executed once
{
  //Initialize I2C communication
  Wire.begin();

  //Initialization of the BNO055
  BNO_Init(&myBNO); //Assigning the structure to hold information about the device

  //Configuration to NDoF mode
  bno055_set_operation_mode(OPERATION_MODE_NDOF);

  delay(1);

  //Initialize the Serial Port to view information on the Serial Monitor
  Serial.begin(115200);
}

void loop() //This code is looped forever
{
  if ((millis() - lastTime) >= 100) //To stream at 10Hz without using additional timers
  {
    lastTime = millis();

    bno055_read_euler_hrp(&myEulerData);            //Update Euler data into the structure

    Serial.print("Time Stamp: ");               //To read out the Time Stamp
    Serial.println(lastTime);

    Serial.print("Heading(Yaw): ");             //To read out the Heading (Yaw)
    Serial.println(float(myEulerData.h) / 16.00);       //Convert to degrees

    Serial.print("Roll: ");                 //To read out the Roll
    Serial.println(float(myEulerData.r) / 16.00);       //Convert to degrees

    Serial.print("Pitch: ");                //To read out the Pitch
    Serial.println(float(myEulerData.p) / 16.00);       //Convert to degrees

    Serial.println();                   //Extra line to differentiate between packets
  }
}

I had the same problem with the Adafruit library. When a Chinese module is used the id needs to be specified in the constructor like this:

Adafruit_BNO055 bno = Adafruit_BNO055(55,0x29);


SdFat Library what is dir_t*? I'm using the SDFat library and the FatFile type has the functions:

  bool FatFile::dirEntry(dir_t* dir)

  Return a file's directory entry.

  Parameters

    [out] dir    Location for return of the file's directory entry.

  Returns

    The value true is returned for success and the value false is returned
    for failure.

And

  uint8_t FatFile::dirName(const dir_t *dir, char *name)

  Format the name field of dir into the 13 byte array name in standard
  8.3 short name format.

  Parameters

    [in] dir The directory structure containing the name.

    [out]    name    A 13 byte char array for the formatted name.

  Returns

    length of the name.

From what I understand, I should be able to pass something like this into the functions:

dir_t Bass;
char dName [13];
FatFile BrowseFile;
BrowseFile.open("/Folder1/File1.txt", O_RDONLY);
Serial.print(BrowseFile.dirEntry(&*Bass));
Serial.print(BrowseFile.dirName(Bass,*dName));
Serial.println(dName);

to which the program should output

1
[Folder1's 8.3 name length]
[Folder1's 8.3 name]

However, I'm getting an error and I can't find any included examples that use these two functions in a sketch. if someone could explain what I'm doing wrong, it would be greatly appreciated.

dir_t * is a pointer to a variable of type dir_t.

I don't know the API to which you refer, but the format for passing it would be:

dir_t Bass;
char dName[13];
BrowseFile.dirEntry(&Bass);
BrowseFile.dirName(&Bass, dName);
Serial.println(dName);


How to work with non-traditional UART baud rates I am trying, unsuccessfully to communicate, using my Arduino Nano, with a custom device at a baud rate of 800 kbit/s.

The Arduino code look like this:

void setup() {
  // Put your setup code here, to run once:
  Serial.begin(800000);
}

void loop() {
  // Put your main code here, to run repeatedly:
  delay(5000);
  Serial.println(0x2be1);
}

When I am trying to debug it with PuTTY the result is:

And when I change the baud rate to 400 kbit/s the result is (as it should be):

Any idea?

The Arduino Nano cannot do 800 kb/s. As you can see in the source
code, the bit duration is rounded to the nearest multiple of
8 CPU cycles. In your case, it is rounded to
3 × 8 CPU cycles, which yields a baud rate of
666.666 kb/s. That is 16% too slow, an error too large for any
communication to be possible.

At 400 kb/s there is no rounding error, so everything works fine.

Edit: Note that if you build your own barebones
Arduino, then either a 12.8 MHz or a 19.2 MHz
crystal should allow you to get that exact baud rate. But then
millis(), delay() and co. would all be off.


Wake up from sleep from pressed button? #include <avr/sleep.h>
#include <avr/power.h>
//This sketch is a metronome, in which each led pin shows one beat.

const int speaker = 13;  //speaker at pin 13
int ts = 6;  //highest led pin
int count = 3;  //"beat 1 pin"
const int keyPin = 11;  //button to change time signature
const int keyPinR = 10;  //button to change rhythm
const int keySwitch = 2;  //sleep mode/wake up button

//All pins below use a pull-up resistor, so the states are inverted
int buttonState = LOW;
int buttonState2 = LOW;
int switchState = LOW;
int silentState = LOW;

int bpm = 120;  //you do not need to know this,
//it's just a variable for the potentiometer to change the tempo

int rthm = 1;  //rhythm
volatile int pressed = 0;
long silent = p;

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

   for(int thisPin = 3;thisPin <= ts;thisPin++)
   {
      pinMode(thisPin,OUTPUT); //initialize thisPin as an output
      pinMode(8, INPUT); //potentialmeter for changing temp
      //Pin 9 to 11, along with pin 2, are all push buttons with pull-up     resistors
      for(int i = 9; i<=11; i++)
      {
         pinMode(i, INPUT);
         digitalWrite(i, HIGH);
      }
         pinMode(2, INPUT);
         digitalWrite(2,HIGH);
   }
}

void loop()
{
   turnOn();
}

void turnOn()
{
    buttonState = digitalRead(keyPin);//key for
    buttonState2 = digitalRead(keyPinR);
    switchState = digitalRead(keySwitch);
    silentState = digitalRead(9);
    //Serial.println(switchState);
    if(switchState==LOW&&pressed==0)
    {
       sleep_enable();
       set_sleep_mode(SLEEP_MODE_PWR_DOWN);
       attachInterrupt(digitalPinToInterrupt(0), interrupt, LOW);
       sleep_cpu();
       //Serial.println(switchState);
    }
    else {
       //The beat starts at pin 3, runs in consecutive pins,
       //and ends at pin 8 at maximum
       if(buttonState==LOW)
       {  //changing time signature - up to 5 beats
           ts++;
           if(ts==8)
           {
              ts = 3;
              //8 - 3 = 5 beats max
           }
        }
        if(buttonState2==LOW)
        {  //changing rhythm - quarter note to eighth, then
          //triplets and sixteenths, back to quarter notes
          rthm++;
          if(rthm==5)
          rthm = 1;
 }

    if(silentState==LOW){//if silent key pressed, go to silence (only LED's showing)
    silent++;
  }

  //The RUN code
  for(int thisPin = 3;thisPin <= ts;thisPin++)
  //LED's blinking beats (thisPin - LED pin (beat number + 2))
 {

 for(int r = 1; r<=rthm; r++)
 {//nested loop for the rhythm
   bpm = pulseIn(8, HIGH);//pin 8 - tempo potentialmeter
   digitalWrite(thisPin,HIGH);//each LED blinks

   pinMode(13,OUTPUT); //pin 13 - speaker

   if(silent%2==0)//Press once, tone, press again, no tone
     noTone(13);
 else
 if(count == 3&&r==1). //first beat is higher
 tone(13,4400,80);
 else if(r==1). //downbeats slightly lower
 tone(13,2500,80);
 else
 tone(13,2200,60);  //off beats even lower
 delay((bpm-52)/rthm);
 digitalWrite(thisPin,LOW);  //turn each off as we proceed to the next beat (LED)
 pinMode(13,INPUT);  //speaker input
}
count++;  //beat++

if(count >ts){//go back to count
count = 3;
}

   }
  }
 }

void noSound()//silence the speaker
{
  noTone(13);
}

void interrupt()//this is where the sleep interrupt starts -               //how can i press it to wake up???
{
    sleep_disable();
    detachInterrupt(0);
    if(switchState==HIGH){
       pressed = 1;
       Serial.println(switchState);
       turnOn(); //go back to the main functional method (?????)
     }
 }

Once the keySwitch button is pressed (pin 2), the arduino goes to sleep; however, the only way to turn it on is by resetting everything. How can I just wake up the Arduino, keeping every state as before the sleep interrupt?

attachInterrupt(digitalPinToInterrupt(0), interrupt, LOW);

should be either

attachInterrupt(0, interrupt, LOW);

or

attachInterrupt(digitalPinToInterrupt(2), interrupt, LOW);

As pin 0 is not an interrupt pin. Also the button is connected to pin 2, not pin 0. digitalPinToInterrupt(0) would actually return -1.


How to delay properly inside ISR I am currently working on a little code which needs to react fast. Here is what I am trying to accomplish:

Using a sine wave phase detector I am detecting every zero crossing and feeding that pulse into the Arduino.

Using an ISR the Arduino detects this zero crossing pulse using RISING. Once one pulse has been detected AND I have pressed a button, I need there to be a delay of 0 - 10ms before switching on an output.

If I don't use an ISR and set a delay of up to 10ms inside the loop, it won't really be 10ms and it will be some other delay, nothing consistent. (I checked with an oscilloscope).

Only when using an ISR and using delayMicrosenconds() inside the ISR I can delay the output consistently for up to 10 ms everytime.

Now I have read that doing this is wrong...Even though it works perfectly. Which better way could I use?

Thanks!

EDIT: While 100% accuracy may not be possible, it needs to be as precise as possible. More important is the repeatability. Using my method I could reproduce the outcome everytime with an accuracy in the nano seconds range.

It's quite simple: You don't.

Instead you use your initial ISR to configure and enable one of the ATMega's Timer peripherals. Set that to the length of your required delay - then the ISR exists.

When the chosen time has passed the timer interrupt triggers, and you use that interrupt to turn on your output.


Serial monitor returns "48" when I enter "0" I am going through an Arduino Learning Book(978-1-59327-448-1) and I've run into the same issue twice now.

When I enter data into the serial monitor, the number that it reads and displays(when asked to print) is way different than what I'm entering.

In diagnosing the problem, I went to https://www.arduino.cc/en/Serial/Read
Copied the code into a new sketch, and tried to run it.
When I Enter 0, I get 48, and a second line saying 10. Enter 1, I get 49 and 10, etc. Here are the results when I enter 0, then 1, then 2, then 3

I received: 48
I received: 10

I received: 49
I received: 10

I received: 50
I received: 10

I received: 51
I received: 10

here is the code I'm using

int incomingByte = 0;   // for incoming serial data

void setup() {
    Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
}

void loop() {

    // send data only when you receive data:
    if (Serial.available() > 0) {
            // read the incoming byte:
            incomingByte = Serial.read();

            // say what you got:
            Serial.print("I received: ");
            Serial.println(incomingByte, DEC);
    }
}

I have the serial monitor set to 9600.
All sketches have worked fine so far, including those that use Serial.print functions, but when I use Serial.read, things seem to get screwed up.

I'm sure I'm missing something stupid, but I've googled around and all the answers are much higher level than just trying to run the code in the Arduino.cc example

Thanks in advance for helping a first timer!

PS: I Tried to get all of the code into the grey box with various line spacing and indenting strategies, but it's not perfect. Does anyone have any tips on that?

Serial.println(incomingByte, DEC);

You told it to print the incoming byte in decimal, so that is what it did. 48 is the decimal equivalent of ASCII '0'.

Change that line to:

Serial.println((char) incomingByte);

That casts the thing you are printing to a character, and then the appropriate version of Serial.println prints it as a character, not a decimal number.

10 is the decimal equivalent of a new line (newline) so that is why you are also seeing 10 printed.

  I need to convert the incoming stuff into integers so that it can see if im guessing right or not

Assuming you mean an integer other than 0 to 9 (like, 42 for example) then you need a bit more work. I have a page about that sort of thing:

http://www.gammon.com.au/serial

Example code:

/*
Example of processing incoming serial data without blocking.

Author:   Nick Gammon
Date:     13 November 2011.
Modified: 31 August 2013.

Released for public use.
*/
// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

In this example, the function process_data is called when there is a complete number to be handled.


Why when I pull an EEPROM index the value returned is garbage? I have an array of colors for my tft screen:

const uint16_t colorTheme [] PROGMEM = {BLACK, WHITE, NAVY, CYAN, RED, GREEN, VERDEAQ, PINK, ORANGE, PURPLE, GRAY, YELLOW};

When I try to use colorTheme [EEPROM.read (2500)] I am returned with a value of any garbage, or a value of 0, and I checked it in read_eeprom and the value of EEPROM.read (2500) is equal to 4, and 4 in mine vector is cyan color, not black or 0 number, why does this go so wrong?

Your array is in PROGMEM, but you are accessing it as if it were in RAM.

You must use pgm_read_word() to access the data in your array.

pgm_read_word(&(colorTheme[EEPROM.read(x)]))

BTW - what Arduino board has more than 2kB of EEPROM?


Simplify if then else statements for Neopixel/compass project I am working on a project where a rotary encoder is generating 0 - 359° output and I am feeding that to a 60 Neopixel ring but I need a way to simplify or come up with a better way of a bunch of if-then-else statements.  Here is some sample code.

// NeoPixel Display
  if ((counter >=3) && (counter <=9))
(
  strip.setPixelColor(0, 255, 0, 0); //set pixel number 1 and set color to red
  strip.show(); //send color to pixel 1 on NeoPixel Ring
)
else if strip.setPixelColor(0, 0, 0, 0);
        strip.show();

  if ((counter >=10) && (counter <=15))
(
  strip.setPixelColor(1, 255, 0, 0); //set pixel number 2 and set color to red
  strip.show(); //send color to pixel 2 on NeoPixel Ring
)
else if strip.setPixelColor(1, 0, 0, 0);
        strip.show();

  if ((counter >=16) && (counter <=21))
(
  strip.setPixelColor(2, 255, 0, 0); //set pixel number 3 and set color to red
  strip.show(); //send color to pixel 3 on NeoPixel Ring
)
else if strip.setPixelColor(2, 0, 0, 0);
        strip.show();

You don't use the correct syntax. I assume you mean:

// NeoPixel Display
if ((counter >=3) && (counter <=9))
{
  strip.setPixelColor(0, 255, 0, 0); //set pixel number 1 and set color to red
  strip.show(); //send color to pixel 1 on NeoPixel Ring
}
else
{
  strip.setPixelColor(0, 0, 0, 0)
  strip.show();
}

And similar for the other colors.

First you see there are a lot of occurences of calls to setPixelColor and show. We make a function of this, where the color and the red value is parameterized:

void setPixel(int pixelNumber, int red)
{
  strip.setPixelColor(pixelNumber, red, 0, 0);
}

Now we can write your code as

// NeoPixel Display
if ((counter >=3) && (counter <=9))
{
  setPixel(0, 255);
}
else
{
  setPixel(0, 0);
}

void setPixel(int pixelNumber, int red)
{
  strip.setPixelColor(pixelNumber, red, 0, 0);
  strip.show();
}

And similar for the other colors.

Now we get rid of the if statements. For the first color this will become:

// NeoPixel Display
setPixel(0, ((counter >= 3) && (counter <= 9)) ? 255 : 0);

Combined with the other colors we get

// NeoPixel Display
setPixel(0, ((counter >=  3) && (counter <=  9)) ? 255 : 0);
setPixel(1, ((counter >= 10) && (counter <= 15)) ? 255 : 0);
setPixel(2, ((counter >= 16) && (counter <= 21)) ? 255 : 0);

void setPixel(int pixelNumber, int red)
{
  strip.setPixelColor(pixelNumber, red, 0, 0);
  strip.show();
}

However, the conditions can be simplified by adding them into the function. So we get

// NeoPixel Display
setPixel(0, counter,  3,  9);
setPixel(1, counter, 10, 15);
setPixel(2, counter, 16, 21);

void setPixel(int pixelNumber, int counter, int lowValue, int highValue)
{
  strip.setPixelColor(pixelNumber,
     ((counter >= lowValue) && (counter <= highValue)) ? 255 : 0,
     0, 0);
  strip.show();
}

If you need to have more checks if a value is in range you can make it a specific function. This will increase the code, but makes it easier to reuse code. So you will get:

// NeoPixel Display
setPixel(0, counter,  3,  9);
setPixel(1, counter, 10, 15);
setPixel(2, counter, 16, 21);

void setPixel(int pixelNumber, int counter, int lowValue, int highValue)
{
  strip.setPixelColor(pixelNumber,
    inRange(counter, lowValue, highValue) ? 255 : 0,
     0, 0);
  strip.show();
}

int inRange(int counter, int lowValue, int highValue)
{
   return ((counter >= lowValue) && (counter <= highValue));
}


Connecting Arduino to internet through HC-06 and then smartphone Can I use HC-06 to connect the Arduino to a smartphone (which I am already doing) and thereafter take the data to the internet?

Yes, but not in quite the way you think.

In this case the smartphone is acting exactly like the PC when you have the Arduino plugged in to it. You have a serial connection. Theoretically you can:

Send a request to the smartphone over the serial bluetooth connection
Write some software on the smartphone to interpret that request and perform some action depending on what the request is

That way the smartphone is then acting like an incredibly expensive and bulky ESP8266.


Can I use a spare Darlington Pair on my ULN2003A to drive a DC motor? I'm successfully running a stepper from my Arduino via a ULN2003A and a secondary power supply. It uses the first four of the seven Darlington Pairs on the chip, leaving three spare.

A) Is there any reason I wouldn't be able to use one of the remaining pairs to drive a standard DC hobby motor? (For the sake of helping future visitors .. what about running three motors off the remaining three pairs?)

B) Do I need anything other than to connect the motor to the chip? (The chip's board has LEDs and resistors on each of pins 1 - 4, but I don't believe they're in series and thus my guess is they can be left off.)

C) The DC motor is on a PWM Pin. Is that the correct way to control its speed?

The image attached shows the setup in case I haven't been clear.

(I could probably just build it and see, but I'm new to Arduino and still scared of the blue smoke if I get something wrong!)

Should work just fine. But you'd have to connect the motor to the positive rail, and since the ULN2003 can only sink current.

Normally when connecting a motor, you'd add a flyback diode. But the ULN2003 already has those inside the chip.

PWM is the easiest way to (somewhat) control the speed of a DC motor.


Does WiFiClient work on a Yún to send data over a certain IP and port to be received by a Python socket? I haven't been able to get the example code from the page WiFi:Client:connect() to work on my Arduino Yún. Is this not how I'm supposed to send data over WiFi to be read by something like a socket?

If not, how would I go about doing so? (This is the only solution I've found from the internet).

No, that code is only for the WiFi shield.  For the Yun you need to look at the Bridge library that is bundled with the IDE. It allows you to run commands and perform actions on the Linux based Atheros portion of the Yun which is what has access to the WiFi.


Need Basic Help with Software Serial I am testing the basic Software Serial example on the arduino website, but I cant get the myserial to print

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

 Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(4800);
  mySerial.println("Hello, world?");
}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

In the example, digital pins 10 and 11 (mySerial) on your Arduino board are used as virtual RX and TX serial lines. The virtual RX pin (pin10)is set up to listen for anything coming in on the hardware RX serial line, and to then echo that data out the virtual TX line (pin11). Conversely, anything received on the virtual RX (pin10) is sent out over the hardware TX.


How can I power an Arduino in a 3-phase environment? I am working on a project which uses an Arduino board. Currently I am testing my device using 2-phase power and it works fine.  I want to use that device in agriculture fields where 3-phase power is available instead. How can I do this?

The very short answer is that the Arduino board itself is designed to be powered by low-voltage DC (but you almost certainly already know this). So what you're really asking, I think, is "can you use the mains power supply that converts mains AC to DC on a three-phase supply?"

The answer to that is a guarded yes. You will need to confirm that you are connecting to a single phase (basically what you were doing in testing) and that the voltage is appropriate for your power adapter.

The abridged version of the gory details follows…

Three-phase supplies are almost always used for motor or other power applications – for a low power device like an Arduino (or even lighting or small appliances) you don't typically need three-phase. What is usually done is to take the power supply for those devices either from phase-to-neutral or phase-to-phase – depending on the configuration of the three-phase supply.

Wikipedia has an article on three-phase power that explains the common connection schemes (Y or star where the three phases are wired to a common point, and delta where they are wired in a triangle). What is significant is that you will typically get a high and a low voltage depending on how you connect to a three-phase system. For example in the US a common Y three-phase service will give you 120 V phase-to-neutral and 208 V phase-to-phase.

A true 3-phase (as in needs to connect to all three phases) low-voltage power supply will probably be quite expensive. But you also don't need one. Unless you are building an "industrial" device all you need is a "normal" low-voltage power supply that is designed for the voltage that you'll be connecting it to.

All you need to do is to confirm the voltage that you'll be using and check that your power supply is rated for it. Many low voltage supplies are designed to be "universal" and you'll see a rating like 100-240 V, 50-60 Hz. That's likely to work on most three-phase supplies as long as the connection isn't phase-to-phase in a part of the world where the high voltage is in the 400 V range.


I2C communication, wrong response With reference from http://www.gammon.com.au/i2c I tried the example there. However I am getting the wrong response and readings. At startup the Master will request for slave address. I should get a reading of "8" but I don't get it. Subsequently, A0 on the slave is connected to a miniature solar panel, that I have tested and it is working, however I keep getting a value -1 from it. No doubt I did modify a little bit to suit my inputs not sure if what I did affected the program.

This is the master code:

    #include <Wire.h>

const int slaveAddressA = 8;

enum {
  cmd_slaveAddress = 1,
  cmd_read_A0 = 2,
  cmd_read_A1 = 3
};

void sendCommand_toSlaveA (const byte cmd, const int responseSize)
{
  Wire.beginTransmission(slaveAddressA);
  Wire.write(cmd);
  Wire.endTransmission();

  Wire.requestFrom(slaveAddressA, responseSize);
}

void setup() {

  Wire.begin();
  Serial.begin(9600);

  sendCommand_toSlaveA(cmd_slaveAddress, 1);

  if(Wire.available())
    {
     Serial.print ("Slave address is: ");
     Serial.println (Wire.read (), DEC);
    }
  else
    {
     Serial.println ("No response to slave address request");
    }

}

void startupTest() {
  Wire.beginTransmission(slaveAddressA);

}

void loop() {

  int val;

  sendCommand_toSlaveA(cmd_read_A0, 2);
  val = Wire.read();
  val <<= 8;
  val |= Wire.read();
  Serial.print("Value of A0: ");
  Serial.println(val, DEC);

  delay(500);

}

This is the slave code:

#include <Wire.h>

const byte my_address = 8;

enum{
  cmd_address = 1,
  cmd_read_A0 = 2,
  cmd_read_A1 = 3
};

char command;

void setup() {

  command = 0;

  pinMode (A0, INPUT);
  digitalWrite (A0, LOW);  // disable pull-up
  pinMode (A1, INPUT);
  digitalWrite (A1, LOW);  // disable pull-up

  Serial.begin(9600);

  Wire.begin (my_address);
  Wire.onReceive (receiveEvent);  // interrupt handler for incoming messages
  Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted
}

void loop(){
  //everything is done using interrupts
}

void receiveEvent(int howMany)
{
  command = Wire.read();
}

void sendSensor (const byte which)
{
  int val = analogRead (which);
  byte buf [2];

    buf [0] = val >> 8;
    buf [1] = val & 0xFF;
    Wire.write (buf, 2);
}

void requestEvent ()
{
  switch (command)
  {
    case cmd_address: Wire.write(0x55); break;   // send slave address
    case cmd_read_A0: sendSensor(A0);   break;   // send A0 value
    case cmd_read_A1: sendSensor(A1);   break;   // send A1 value

   }

}

Also I'm wondering if I have to add a "Wire.begin(8);" at the slave program setup. ---------------------------I would like to know what did I do wrongly?

UPDATE: The 2 boards are now communicating with one another. However, requested address gives a '85' instead of an '8'. As for input A0, for example it should show '700' with a little bit of variant, but now it shows a repeated pattern of e.g '0 0 0 400 500 800 1040 1040 1040 800 500 400 0 0 0'

When you send 'buf', how do you know that buf[0] is transmitted first and buf[1] is transmitted second ? Not long ago a bug in Wire library was fixed and it is now allowed to use multiple Wire.send() in the requestEvent() function. I suggest to send two bytes in sendSensor() in the Slave without using the 'buf'.

When you request the Slave addres, you send 0x55. That is not the Slave address. Do you receive 0x55 ?

It is not needed to remove pullup resistors from the analog input pins. It is also not needed to set the pinMode for those pins. You can use analogRead() without something else.

Did you connect the GNDs ? And did you connect SDA to SDA and also SCL to SCL. Which Arduino boards do you use ? Do you know that you can start the Arduino IDE twice, each connected to a board and each with its own serial monitor. That way you can work on both sketches at the same time.
As soon as the Slave is running with Wire.begin(8), the Master can run a i2c_scanner and it should find I2C address 8. That is the first test to verify that the I2C bus is working.


Is Roboteq motor driver compatible with Arduino? I'm planning use Roboteq motor driver for 24V brushed DC motor but I can't be sure that it's true or wrong. You know, Roboteq controller is too expensive and I don't want to spend money in vain. Have you any experience this controller? Are they compatible with Arduino?

http://www.roboteq.com/index.php/roboteq-products-and-services/brushed-dc-motor-controllers/mdc2230-detail  Roboteq Controller Link

I also think, Pololu RoboClaw driver. https://www.pololu.com/product/1499 I don't know is it enough for wheelchair. Because, I already have used Pololu VNH5019 and it is not enough. (synchronicity and noise problems etc.)

If you have any ideas, I will be glad. Thank you.

It is not directly supported. But the device description lists RS232 port that can be interfaced with an Arduino using a TTL to RS232 converter. The description also mentions "several Analog, Pulse and Digital I/Os which can be remapped as command or feedback inputs, limit switches, or many other functions" so it is totally possible to control the controller with an Arduino, but depending on the method you choose it may require some effort.


Arduino Pro Mini maximal and recommended current per pin In Arduino Pro Mini (3.3V) specs indicated the maximal and recommended current per pin, 40mA and 20mA respectively. Does these values means input current (i.e. safe input current Arduino can handle) or output current?

It is the amount of current the pin can source or sink when in OUTPUT mode.

That is, the amount of current that can flow from the pin to ground, or can flow from VCC into the pin.

You can understand it better if you learn how a GPIO pin works.


Arduino Packet for Bluetooth I'm having trouble figuring out how to start my project. The objective is to control a robot with four servo motors and six DC motors through bluetooth. I have a bluetooth shield from Adafruit and I'm using the Arduino UNO. Ideally, I want to control this robot by sending it packets through Processing. The problem is I don't know how to create a packet with a header, payload, and checksum. I can't find any examples; can anyone help me find something to help me get started?

First, depending on the degree of reliability you need, you may not actually have to do this yourself, as the bluetooth implementation will already invisibly-to-you add, verify, and remove a packet and checksum framing around your data.  But let's assume you want to add your own as well.

A packet is a batch of data to be transmitted as a contained unit.  It may or may not contain exactly one useful message, but it is quite convenient if it does, and since you will be doing your own packetization (at this level) you can make sure that it does.  So basically you will transmit something that has a structure, for example:

Hi, I'm a packet
attention HAL
"Open the pod bay doors"
The bytes in this message should add up to xx if you ignore the overflow
That was a packet

There are countless ways you could implement this, but your life will be a lot easier if you make both the messages and the packet structure human readable, so that you can watch on the serial monitor, and perhaps even type manually.  So let's say you did something like

M1=200/BF\n

For simplicity sake, instead of having a "Hi I'm a packet" header, we just use the newline character '\n' to mark the end of a packet, and assume that whatever comes next is the start of a new packet.  Further, since bluetooth is already creating a one-to-one link, you don't need to address who you are talking to.

Now we have a message, for example "M1=200" meaning "drive motor 1 at PWM level 200" (out of 255).

I'm somewhat randomly choosing the '/' character to mark the division between the message body and it's checksum.

"BF" might be the low two hex digits of adding up all the previous bytes in this message (it's not, I just picked something random).

And finally you have your newline to mark the end of a message and the end of a packet, since in this scheme we've decided that 1 packet = 1 message.

For extra fun, if the robot itself is not dangerous, you can make a test mode where the receiver will accept messages with no '/' and checksum, and only check the checksum on those where it is present.  This would allow you to manually type messages into a terminal when you are experimenting.  Or you can make your own specialized terminal program which calculates and appends a checksum each time you press return


How to increase SD card write speed in arduino I'm creating a data-logger system which logs data in SD card at a high speed of about 20000-30000 bytes per second. But the SD library in arduino currently writes data at about 4500-5000 bytes per second which is too slow.

I've read this hack to improve the write speed, but I'm wondering if a more direct approach is possible, maybe by adjusting the SPISettings.

OK. So, I tried the SDFat lib. This library is definitely better than the default SD library that comes with adruino.
But that is not how I solved my problem of low data-rate.

I followed the instruction of the author of SDFat library from this post.

According to fat16lib, to increase the data rate we need to use flush() wisely. We would want to write() the data in each cycle, but we only need to flush() once every 100 cycles or so depending on how much data is being written in each cycle. Also, be sure to keep the flag in SD.open() as 'O_WRITE | O_CREAT' instead of 'FILE_WRITE'.

This sure increased the speed by a great factor. But I needed more!

Storing the data in binary (check out this blog) improved the performance even more.

My current speed is approximately 100-120 KBps (that's kilo bytes) with a class 4 SD card!

Finally, I want to thank you guys for your help.


How do I use ultrasound to track a moving object? I'm trying to create a small scale, dumb-downed version of the pitch tracking systems used to detect the speed and direction of baseballs.

I'm currently working with an HC-SRO4 sensor and an Arduino, but I'm unsure how to expand because a single sensor can't track an object that's not moving linearly (ie rising or falling as it moves). My team's idea was to make a grid of multiple HC-SRO4's connected to one Arduino, but we're worried that the delay will be too large if we try to turn them on sequentially to avoid interference.

How can we use ultrasound to track a moving ball?

Yes you can use ultrasound to track a moving target, but I really doubt it could be done with an Arduino.

You need to be able to ping the object at least 3 times in the time it takes to move your beam width.  3 times because if you know where it is with the centred ping you need to calculate the direction of travel by pinging either side of the centre to see if it is there.

You then need to track it in three dimensions.  To do this you will need multiple sensors ideally at least 3 for 2D and 3 for 3D, so at least 6.  3 sensors in a plane will give you a reasonable degree of accuracy, but you beam width is key to this, the narrower the better.

Now you have to triangulate the position of the object, well actually work out the area of probability (for both planes) you never 'know' where it is really.

Oh and all 6 sensors need to have different frequencies to prevent interference, you then need to add in reflection processing to reduce false signals.

Its just much easier to buy a Pixy camera and download the software that they have for visually tracking your balls.


SIM900A A6 module Arduino +CME error 58 I've recently bought a SIM900A A6 GSM module. Whenever I send a command it gives an error: +CME error 58.

Does anybody know what this means and how to solve it?

Your sim card is probably protected by a PIN. Easiest way to get it working is to put the SIM into a normal phone and remove the PIN protection.


ADC port manipulation I was modifying this ADC Touch implementation, namely switching analogRead and pinMode to what I thought would be port manipulation equivalents.

I get very different readings (better and more stable in my case).

So, what I think is equivalent is actually quite different. Can someone point the differences to me?

Original:

    pinMode(ADCChannel, INPUT_PULLUP);

    ADMUX |=   0b11111;
    ADCSRA |= (1<<ADSC); //start conversion
    while(!(ADCSRA & (1<<ADIF))); //wait for conversion to finish
    ADCSRA |= (1<<ADIF); //reset the flag

    pinMode(ADCChannel, INPUT);
    _value += analogRead(ADCChannel);

Modified:

    DDRC &= ~(1 << ADCChannel);
    PORTC |= (1 << ADCChannel);

    ADMUX |=   0b11111;
    ADCSRA |= (1<<ADSC); //start conversion
    while(!(ADCSRA & (1<<ADIF))); //wait for conversion to finish
    ADCSRA |= (1<<ADIF); //reset the flag

    DDRC &= ~(1 << ADCChannel);
    _value += analogRead(ADCChannel);

Your modified code doesn't disable the pullup on the pin.

PORTC &= ~_BV(ADCChannel);


Sketchy Wemos D1 mini Pro Recently, I bought a "ThingPulse ESP2866 Wifi Color Display Kit". I bought the kit before reading the reviews and finally read them the other day. Some of the reviews seem fake but a couple of them say that the Wemos D1 mini pro is being used to "steal credit cards" and other information. The bad reviews claimed that when they plugged the wemos into a power source, a wifi network named "ESP_xxxxxx" appears and thats how their data is stolen. I plugged the Wemos that came in my kit to a power source and a wifi network starting with "ESP..." appeard. I was wondering if this is a valid concern or if its just conspiracy. I am not very informed on cybersecurity and data security so I thought this would be the best place to ask. Please let me know if you'd like anymore information.  Thank you!

It's pure conspiracy, paranoia, or people just generally not having the slightest clue what they have bought. By default the ESP8266 is in Access Point mode, and named ESP_[last 6 chars of MAC address]. It will have an IP address in the range 192.168.4.x. And that is all.

It can't do anything else until you actually program it to do something.

Part of the "problem" is probably that the ESP8266 remembers WiFi settings independently of the sketch that is running on it. It's only the WiFi settings it remembers, though - not what to do with any data that travels over WiFi. That is purely down to whatever sketch you install.

Unless you manually program it so it connects to your WiFi, or add extra hardware for other communications, the device can not, and will never be able to, send any data to anyone, anywhere, ever. Full stop.


Multiple definition of "..." Compiler Error I am creating a simple library to test how multiple files in an Arduino program works. I have three files. MotorController.ino:

#include <motor.h>

void setup() {
   motorInitialize();
}

void loop() {

}

motor.cpp:

#include "motor.h"

void motorInitialize() {

  for (int i = 0; i < 4; i++) {
     motorArray[i].writeMicroseconds(2000);
     delay(1500);
     motorArray[i].writeMicroseconds(2000);
     delay(1500);
  }
  delay(1000);

}

and motor.h:

#ifndef _motor_h_
#define _motor_h_

#include "Arduino.h"
#include <Servo.h>

Servo motor1, motor2, motor3, motor4;
Servo motorArray[4] = {motor1, motor2, motor3, motor4};

void motorInitialize();
#endif

When I try to compile the program, I get the error:

libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor1'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor2'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor3'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motor4'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries/motorLibrary/motor.cpp.o (symbol from plugin): In function `motor1':
(.text+0x0): multiple definition of `motorArray'
sketch/test.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

I have read similar posts on this issue, but none of the solutions seem to work for me. I've followed the instructions on the Arduino website on how to create a library, and that doesn't seem to resolve this issue.

Although the motor (global) variables are defined in a header files, they are included in both cpp files, thus defined twice.

Make them extern, and than define them in the motor.cpp file.

In motor.h, change

Servo motor1, motor2, motor3, motor4;
Servo motorArray[4] = {motor1, motor2, motor3, motor4};

to

extern Servo motor1, motor2, motor3, motor4;
extern Servo motorArray[4];

In motor.cpp, add:

Servo motor1, motor2, motor3, motor4;
Servo motorArray[4] = {motor1, motor2, motor3, motor4};

As a side note, use consts for values 4 and 2000.


How to convert a string to long int? I'm new to Arduino and my first project is an RFID reader. since I need a lot of known tags list , i have a problem with not enough memory. for that reason I want to convert strings like :  "426d9244", "1265dd39"... to a long int. I know it's been asked but as a new programer I find it hard to understand. an example would be very appreciated also.

If all those are known tags, you can put them in the source code as
32 bit integers. No
need to convert. Or rather, let the compiler do the conversion:

const uint32_t ID_num[ARRAYSIZE] PROGMEM = {
    Oxbcc0f1c3, Ox821a7d39, Ox4924887c, ...
};

When you read a tag number in hex, in order to compare it with the known
tags, you convert it to the same type using strtoul() from
avr-libc:

uint32_t tag_id = strtoul(tag_string, NULL, 10);


How do you remove an item from array arduino? Is there a way that can change {3, 5, 3, 6} to {3, 5, 6} with a function? I checked all the arduino forums but they don't give the answer i need (just delete 1 item from an array with a function like delete(myArray, 2)).

There is no such concept in C. Arrays are a fixed size and that size can never be changed. You can't "delete" an entry. You can replace one with something else, and you can introduce the concept of a variable that says how many entries the array has, but you can't delete one.
So you could:

Keep a count of how many entries are in the array
Shuffle down all the entries one space so the unused one is at the end
Decrement the count of entries

So in your example {3, 5, 3, 6} becomes {3, 5, 6, 6} and your "count" holds 3 to say the first three entries are valid and to ignore the last.
Alternatively you can introduce the concept of "end of array". C strings do this with the NULL character (0). Anything before that character is valid, and anything from that character onwards is ignored.  So say you nominated the value -1 to be "end of array" you could have, after again shuffling down the values: {3, 5, 6, -1}.
You could also have -1 (or whatever you chose) indicating an "invalid" entry, so your array would be {3, 5, -1, 6} and you would ignore the -1 entry in your code.


Execute Code on power off? Arduino newbie here.

I'm thinking about building an Arduino-based light switch to control the Philips Hue light system in my living room. I have standard wall light switches that power ceiling lamps, and I basically want all Hue lamps that are scattered around the room to be on when the switch is on, and off when the switch is off, so that I don't necessarily need the app or the Hue remote to turn the room's lights on.

My idea is to install an Arduino on the ceiling instead of a normal lamp, so that its power supply is switchable through the light switch.

I would configure it as a Hue remote control, e.g. with ArduinoHue; if all works well, this would control the Hue lamps directly via ZigBee or via WiFi through the bridge - in both cases without having to use additional wiring.

Whenever it gets power, I would have it turnOn() all lamps, and whenever its power supply is turned off, I would have it turnOff() all lamps.
The first part seems simple to me, the second part - not so much.

So here's my question:
Can I execute code in the event of the Arduino losing power, i.e. turn off my Hue lights with its last energy before shutting down? Is there maybe some hardware configuration that would allow me to detect the power off event and retain enough energy through a battery or capacitors to still run the code?

I have never worked with Arduino before, but I do have some colleagues that can help me out when there's trouble.

You could do what you want as you describe it, but are making things harder for yourself that you need to. If you can access the circuit from the switch at or near the switch (which should be 'easy' in most cases) then your system does not have to be depowered when the lighting circuit is as you will have access to the mains AC voltage on either side of the switch.

If you do wish to depower the processor when the lights are turned off you can easily add either a backup battery or a capacitor that runs the processor for "long enough". You can also run a processor in "sleep" mode at extremely low power so that it is always running so have no 'wakeup time". And it is possible to power up a processor so that the delay is not noticeable for practical purposes.

However, as Hue Bulbs are Zigbee controlled, with provision ofr both iOS and Android control,  you should be able to control them via Zigbee directly without any connection to their wiring.

Hue control

Hue specifications


Make device based on CH340G working as keyboard There is small board with gyroscope. Controller - Atmega 8a, com-usb chip is CH340G. Board is handmade but not by me so I don't sure is it Arduino clone or not. It works with "ch341ser" driver on the computer and is used in small video game writed on java. This game is ran by .bat file where I specify COM port number, game listen this port in code.

I need to do anything to make computer understand gyro tilt as arrow keyboard buttons commands. In other words I need to write a driver or smth else to make computer understand device as USB HID keyboard. Is it possible to do it programmatically and how to do that?

No, it's not possible. The device enumerates as a USB serial device, and the only way to change that is to change the internal silicon of the device.

The closest you could do is (though I have no clue how on Windows) write (or if you are lucky, find) a program that reads serial data through the COM port and somehow injects keyboard commands into the input subsystem of the operating system.


I can't run shell commands on Linux through AVR sketch (Arduino Yun) I'm a little confused with some Process.h methods.
I'm trying to run the command "nc 192.168.1.15 9911" to the Linux processor through a sketch.
The appropriate netcat listener is waiting on another computer. Arduino Yun is on the same network with thie computer via WiFi.
When I execute this command through SSH connection on Arduino Yun it works fine, but I can't figure out how it's done through a sketch.
This is my code:
#include <Process.h>

Process p;

void setup() {
   Bridge.begin();
   Serial.begin(9600);
   delay(2000);
   p.begin("nc");
   p.addParameter("192.168.1.15 9911");
   p.run();
   //while (!p.running()) {};

 }

 void loop() {
    if (p.available() > 0) {
    Serial.println("test");
 }
}

This code doesn't seem to work, p.available() nerver executes even if I send data packets.
I also tried p.runShellCommand("nc 192.168.1.15 9911"); with no luck.
It seems that the commands never reach the Linux command line.
Any insights?

There's a few things wrong with your program, some more obvious than others.
First, you have to put each parameter to your shell command in a separate addParameter() call. Otherwise it treats all the parameters as a single parameter and tries to connect you to an address of 192.168.1.15 9911 instead of to port 9911 of address 192.168.1.15.
Secondly you should use runAsynchronously() instead of run() otherwise your sketch blocks at that point until nc terminates. If that never happens then your sketch never gets to the point where it can read the data.
Here is an adaption of your sketch that works for me:
#include <Process.h>

Process p;

void setup() {
    Bridge.begin();
    Console.begin();
    p.begin("nc");
    p.addParameter("192.168.1.15");
    p.addParameter("9911");
    p.runAsynchronously();
}

void loop() {
    static uint32_t ts = millis();

    if (millis() - ts > 1000) {
        Console.println(millis());
        ts = millis();
    }

    if (p.running()) {
        while (p.available()) {
            Console.write(p.read());
        }
    } else {
        Console.println("Restarting process");
        delay(100);
        p.begin("nc");
        p.addParameter("192.168.1.15");
        p.addParameter("9911");
        p.runAsynchronously();
    }
}

It also re-runs nc if / when it terminates. There's also a "heartbeat" printing of millis() so that you can see the sketch is running.  It uses the console, not Serial, for its output, so SSH in to the Yun and telnet localhost 6571 to view the output.


How to make data sent by Python (via serial connection) wait for Arduino to finish current task? I am trying to make my Arduino micro-controller and my Mac talk together, and I have created a functional serial connection. My computer is sending data to my Arduino, and my Arduino is sending a 1 when it is ready to receive a new piece of data.

I have created an if-else statement (Python script below), which is either sending a new line of data to the Arduino or waiting for the Arduino to be ready for receiving a new line of data.

The problem is that ser.read() in the first part of the Python script always returns 1, which means that the script is sending the individual data lines faster than the Arduino connected stepper motors can possible react.

In the Arduino script you can see that I am sending the state-status in the first line of the serialEvent() function, which in my world should let the Arduino finish its job, before a new "task" is coming. However, it is for some reason not working. Can anybody help me out here?

Python script

import os
import time
import serial

# Name of csv file with drawing coordinates
csvFile = "scaled_coordinates.csv"

# Create serial connection
ser = serial.Serial(port='/dev/tty.usbserial-A9005bDh', baudrate=9600)

wd = os.getcwd()
myFile = open(wd + "/coordinates/" + csvFile)

state = '1'

while True: # Exits when there is no more lines to read
    print "test"

    if state == '0': # Wait for Arduino to be ready
        state = ser.read()

    elif state == '1': # Send one more line to Arduino
        line = myFile.readline()
        if not line:
            break
        print line
        ser.write(line)
        state = '0' # Wait for Arduino before reading next line

ser.close
myFile.close

Arduino loop function

void loop() {
  serialEvent(); // Call the serial function
  if (coord_complete) {
    // Steps to move from currrent to new point
    target1 = steps(x_current, y_current, x_new, y_new, 1);
    target2 = steps(x_current, y_current, x_new, y_new, 2);

    // Start moving
    stepper1.move(target1);
    stepper2.move(target2);

    // Update current position
    x_current = x_new;
    y_current = y_new;

    // Reset variables
    x_complete = false;
    y_complete = false;
    coord_complete = false;
  }

  // Stay in while loop until steppermotors is done
  while ((stepper1.distanceToGo() != 0) && (stepper2.distanceToGo() != 0)) {
    stepper1.run();
    stepper2.run();
  }
}

Arduino serialEvent function

void serialEvent() {
  // EDIT : PUT SERIAL.WRITE INSIDE IF STATEMENT //
  if((stepper1.distanceToGo() == 0) && (stepper2.distanceToGo() == 0)){
    Serial.write('1'); // Tell Python that Arduino is ready for one more line
  }

  while (Serial.available() && coord_complete == false) {
    char ch = Serial.read(); // Get new character
    // EDIT : REMOVE THIS LINE //
    Serial.print(ch);

    // If digit; add it to coord_string
    if (isDigit(ch)) {
      coord_string[index++] = ch;

    // Else if ch is ","; then rename to x_new
    } else if (ch == ',') {
      coord_string[index++] = NULL;  // Finish coord_string
      x_new = atoi(coord_string);    // Convert to integer
      x_complete = true;             // Change x_complete to true
      index = 0;                     // Reset index
      memset(coord_string, 0, sizeof(coord_string));  // Reset coord_string
    // Else if ch is a new line; then rename as y_new
    } else if (ch == ';') {
      //Serial.write('0');
      coord_string[index++] = NULL;
      y_new = atoi(coord_string);
      y_complete = true;
      index = 0;
      memset(coord_string, 0, sizeof(coord_string));
    }

    // Ends while-loop when true
    coord_complete = x_complete * y_complete;
  }
}

Edit

I have changed a bit in the first few lines of the serialEvent function (See comments).

Here is a sample of the text file I am reading from:

239,275;
1100,275;
300,400;
200,400;
200,300;

If I'm getting things right, your program fails in the above:

  when you send the first message in python, you set state = 0. In
  arduino you enter the serialEvent function and while is triggered. You
  get the first char and send it through Serial.print (but this char
  will be send to python!!!). For the sake of example let's say the
  first char you get from cvs is '2'. At this point let's hold on a
  sec and look what happens in python. State was '0' but as you have
  used in arduino Serial.print(ch); now state will be updated with
  '2'. This will cause no more triggers of the if-else statements in
  python.

  edit:

  By now, and also as a debug, add this lines at your code:

if state == '0': # Wait for Arduino to be ready
    state = ser.read()
    if state != '1':
        print "state: " + state
        state = '0'

  However if csv file contains '1's values this will also cause a
  problem. Do you really need that Serial.print(ch) in arduino?

EDIT The new version since comments
Basically if you are trying to do things before new coordinates, you have to do things in a sequential way. You only ask for info after making all the moves. This is the code I've used to test.
Note: I had to adapt your code because was missing the complete arduino code to test it. So I kinda simulated the motor moving etc with delays. Please adapt to your original code

#include <string.h>

bool coord_complete = false;
byte stepper1_disToGo = 0, stepper2_disToGo = 0;
// debug things
int led = 13;
bool led_state = true, x_complete, y_complete;
char coord_string[256];
int index = 0, x_new = 0, y_new = 0;

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

void loop() {

  serialData(); //ask and process more data

  /*
    // Steps to move from currrent to new point
    target1 = steps(x_current, y_current, x_new, y_new, 1);
    target2 = steps(x_current, y_current, x_new, y_new, 2);

    // Start moving
    stepper1.move(target1);
    stepper2.move(target2);

    // Update current position
    x_current = x_new;
    y_current = y_new;

    // Reset variables
    x_complete = false;
    y_complete = false;
  */
  delay(2000); //replace to simulate actions
  stepper1_disToGo = 10;
  stepper2_disToGo = 10;
  coord_complete = false;

  // replaced to simulate
  /*
    // Stay in while loop until steppermotors is done
    while ((stepper1.distanceToGo() != 0) && (stepper2.distanceToGo() != 0)) {
    stepper1.run();
    stepper2.run();
    }
  */
  while ((stepper1_disToGo != 0) || (stepper2_disToGo != 0)) {
    stepper1_disToGo --;
    stepper2_disToGo --;
    digitalWrite(led, led_state); // is moving!!!!
    delay(100);
    led_state = !led_state;
  }
}

/*
   you try to use the serialEvent  but the structure of
   your code and the verifications make it act like sequential.
   If you only want to make things after all steps are done there
   is no need for the serialEvent function
*/
void serialData() {
  /*
     This will never be false because you are stuck in the while

    // EDIT : PUT SERIAL.WRITE INSIDE IF STATEMENT //
    if((stepper1.distanceToGo() == 0) && (stepper2.distanceToGo() == 0)){
    Serial.write('1'); // Tell Python that Arduino is ready for one more line
    }
  */
  //EDIT: wait for info
  while (Serial.available() < 1) {
    Serial.write('1'); /// Tell Python that Arduino is ready for one more line
    delay(500);// ask for info sometimes
  }
  while (Serial.available()) {
    char ch = Serial.read(); // Get new character

    // If digit; add it to coord_string
    if (isDigit(ch)) {
      coord_string[index++] = ch;

      // Else if ch is ","; then rename to x_new
    } else if (ch == ',') {
      coord_string[index++] = NULL;                   // Finish coord_string
      x_new = atoi(coord_string);                     // Convert to integer
      x_complete = true;                              // Change x_complete to true
      index = 0;                                      // Reset index
      memset(coord_string, 0, sizeof(coord_string));  // Reset coord_string

      // Else if ch is a new line; then rename as y_new
    } else if (ch == ';') {
      coord_string[index++] = NULL;
      y_new = atoi(coord_string);
      y_complete = true;
      index = 0;
      memset(coord_string, 0, sizeof(coord_string));
    }
    //EDIT: change to AND verification
    // Ends while-loop when true
    coord_complete = x_complete && y_complete;
  }
}

The structure of your loop should be:

ask for data and wait for it
Read data and parse it
Calculate steps needed
move servos till new positions
repeat

this should be your new code more or less if no mistakes were made because can't really test this version (is missing the variables declarations setup, includes etc...)

void loop() {

  serialData(); //ask and process more data
  // Steps to move from currrent to new point
  target1 = steps(x_current, y_current, x_new, y_new, 1);
  target2 = steps(x_current, y_current, x_new, y_new, 2);

  // Start moving
  stepper1.move(target1);
  stepper2.move(target2);

  // Update current position
  x_current = x_new;
  y_current = y_new;

  // Reset variables
  x_complete = false;
  y_complete = false;
  coord_complete = false;

  // Stay in while loop until steppermotors is done
  while ((stepper1.distanceToGo() != 0) && (stepper2.distanceToGo() != 0)) {
    stepper1.run();
    stepper2.run();
  }
}

void serialData() {

  //EDIT: wait for info
  while (Serial.available() < 1) {
    Serial.write('1'); /// Tell Python that Arduino is ready for one more line
    delay(500);// ask for info sometimes
  }
  // we got info!!!
  while (Serial.available()) {
    char ch = Serial.read(); // Get new character

    // If digit; add it to coord_string
    if (isDigit(ch)) {
      coord_string[index++] = ch;

      // Else if ch is ","; then rename to x_new
    } else if (ch == ',') {
      coord_string[index++] = NULL;                   // Finish coord_string
      x_new = atoi(coord_string);                     // Convert to integer
      x_complete = true;                              // Change x_complete to true
      index = 0;                                      // Reset index
      memset(coord_string, 0, sizeof(coord_string));  // Reset coord_string

      // Else if ch is a new line; then rename as y_new
    } else if (ch == ';') {
      coord_string[index++] = NULL;
      y_new = atoi(coord_string);
      y_complete = true;
      index = 0;
      memset(coord_string, 0, sizeof(coord_string));
    }
    //EDIT: change to AND verification
    // Ends while-loop when true
    coord_complete = x_complete && y_complete;
  }
}


How do I connect this to my breadboard? I just purchased this Grove RTC. It includes a cable presumably to connect it to a breadboard and/or Arduino, but the pin holes on this cable are much smaller than those on a breadboard or Arduino.

How/where would I connect this in the case of using an Arduino Uno?

Either use jumper wire, or pull the connectors from the Housing and connect them with male connectors.


How can I exactly put my sensor at 4 Hz readings? I'm using the grove GSR sensor: http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor with this code:

const int GSR=A0;
int threshold=0;
int sensorValue;
const long interval = 1000;
void setup(){
  long sum=0;
  Serial.begin(9600);
  delay(1000);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
   Serial.print("threshold =");
   Serial.println(threshold);
  }

void loop(){
  int temp;
  sensorValue=analogRead(GSR);
  Serial.println(sensorValue);
  temp = threshold - sensorValue;
  delay(250);
  }

There is the delay way to skip milliseconds or the millis() function. Do you have ideas on how can I implement it? The delay has the problem that doesn't consider the time the sensor uses to read the data.

Here's what I am trying

const int GSR=A0;
int threshold=0;
int sensorValue;
const long interval = 1000;
unsigned long startTime=millis();

void setup(){
  long sum=0;
  Serial.begin(9600);
  delay(1000);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
   Serial.print("threshold =");
   Serial.println(threshold);
  }

void loop(){

  if((millis() - startTime) % 250 == 0) {
   int temp;
  sensorValue=analogRead(GSR);
  Serial.println(sensorValue);
  temp = threshold - sensorValue;

  }
  }

The difference between your first code and the second one is that the first one is blocking execution when it reaches the delay function, but the second code keeps running without being blocked.

Now your algorithm has a drawback, the loop may or may not reach the if condition exactly when the modulo is strictly equal to 0. So you may prefer to use something like :

unsigned long T = millis();

...

if( millis() - T >= 250 ) {
    ... // sensor stuff
    T = millis();
}

This idea is also presented in this article https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay.

Another approach is to use Timers and Interrupts, but this is far more complicated (http://playground.arduino.cc/Code/Timer1).


Avoid a Pro Micro waking up a PC? I have an Arduino Pro Micro mimicking as a HID, connected to a PC.

The PC BIOS is configured to wake from keyboard events - it is switched on by hitting a key on the regular keyboard. This is a wanted feature and should stay.

Unfortunately, it also wakes when the Arduino sends HID events, which is understandable and pretty obvious, but to be avoided.

Is there something in the USB protocoll, or even in the Arduino HID libraries, that lets me tell the chip to either not wake up the host (unlikely, I guess); or so that I can detect when the PC has shut down, so I can tell the Arduino to go sleeping as well until the PC wakes up again?

EDIT: I am using the "HID-project" USB library (HID 2.4.3) from https://github.com/NicoHood/HID.

Assuming you are using windows, on the device manager you can access each device's properties (power management tab), where you can allow or not each device to wake your system up.


Yet another display 16x2 not working with arduino I found hundreds of questions about display not working with arduino.
However, no matter how trivial this looks like I am having the same problem I cannot understand by reading the other posts.

I have an Arduino micro connected to a display from the adafruit kit

RGB LCD SHIELD KIT W/ 16X2 CHARACTER DISPLAY

I haven't been able to understand whether positive or negative, but I think from the picture is RGB positive.

I have connected everything as shown in the diagram in this page:

LCD "Hello World!"

Obviously changing the pins as I have

RS at 8
E at 7
d4 = 12
d5 = 11
d6 = 10
d7 = 9;

The potentiometer changes the contrast, if I saturate it I can see the black boxes.

In the code put this as

const int rs = 8, en = 7, d4 = 12, d5 = 11, d6 = 10, d7 = 9;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

I checked with the multimeter whether the soldering is good and it carries the signal at the end of the wires.

and the rest as the example in the link,

This is my mess (please ignore the other arduino and the thermocople which is not connected, the other orange wire goes to GND of the Arduino).

Any ideas that might help?

disconnect the E line, power up the system and adjust the contrast so you see 1 black bar on the first line;
reconnect the E line and see if your code is working.
go from there.


Read frequency to voltage with Arduino How to read frequency into voltage with Arduino with an external source of frequency of 0-1Khz max?

In the past I used the LM2917 for this purpose:

http://www.ti.com/lit/ds/symlink/lm2907-n.pdf

That IC is a frequency to voltage converter, so it perfectly suits your need. According to some quick calculations I made it can go to some tens of kHz, so if your signal is up to 1kHz it should be fine.

Now, this is the answer to your question. But... You can easily read the frequency directly with the arduino... If your purpose was to read the frequency, I suggest you to read something about the X-Y problem