Model Rocket Sensors My idea is to record the acceleration/altitude of a small model rocket launch using these sensors and record all the data onto a microSD card which I'll retrieve afterwards. I'd like to be able to plot all of the data to analyze the performance of the rocket. This data will also help compare the experimental results to the theoretical ones.

Accelerometer

OpenLog/SD Card

(Was only allowed two links so couldn't include barometer)

I have a few questions to make sure that my logic is sound when trying to design this circuit;

1.) Since the OpenLog contains the ATmega328 microcontroller I was going to use the Arduino to write the instructions to this which will initialize the two sensors and start logging data. Is this the correct way to do this? From what I could tell the other sensors did not contain any EEPROM/Flash so there was no way to store any code on there.

2.) If I have multiple sensors running at the same time is this going to cause a data conflict when writing to the SD card? Would it be possible to save two different .txt files, one for each sensor?

Thanks

The OpenLogger was designed to be paired with and Arduino Pro or Arduino Pro Mini and just log the serial output from one of those. You could theoretically use the OpenLogger itself to do the sensor reading and writing, however, the I2C pins that your sensor needs haven't been broken out on the OpenLogger.

This means if you really wanted to make this happen, you would have to hand solder those pins and break them out yourself. After that the process is pretty straightforward. SparkFun provides both the source code and directions on programming it.

If trying to break those out is a little too tricky, you can either pair it with one of those Arduino models and use it to read the data, or find another similar logger device that has more pins broken out.

Two answer the second part of your question, reading multiple sensors isn't a problem. Usually the way these sensors work is you send a request for data to them and they return the reading, so you would just request from the first sensor, request from the second sensor, write out to the file.

You can write to two different files no problem eiteher. I would not however, recommend writing to two different files. Switching from one file to another, back and forth introduces a little extra overhead which will slow down your loop. In rocketry, things happen very fast, and you'll probably want keep your loop running as fast as possible. I would recommend just writing to a single file and include data from both sensors probably something along the lines of time,accelX,accelY,accelZ,bar.


What is an ICSP pin? What is an ICSP pin? I have read that it is an AVR and a tiny programming header for the Arduino, but what is an AVR and what does an ICSP pin do?

ICSP stands for In Circuit Serial Programming, which represents one of the several methods available for programming Arduino boards.  Ordinarily, an Arduino bootloader program is used to program an Arduino board, but if the bootloader is missing or damaged, ICSP can be used instead.  ICSP can be used to restore a missing or damaged bootloader.

A typical Arduino ICSP header has six pins, arranged 2x3.  The article Connecting the Programmer:
In-Circuit Serial Programming (ICSP) at Sparkfun describes some of the functions of ICSP pins, which include MISO, MOSI, SCK, V+, Ground, and Reset.

Each ICSP pin usually is cross-connected to another Arduino pin with the same name or function.  For example, MISO on an Uno or Nano's ICSP header is connected to MISO / digital pin 12; MOSI on the ISCP header is connected to MOSI / digital pin 11; and so forth.  Note, MISO, MOSI, and SCK pins taken together make up most of an SPI interface.

Several Arduinos, including the Uno, have two ICSP headers.  One of them is for use with the ATmega328 (or similar), and the other for use with the ATmega16U2 (or similar) chip that implements USB. When present, this  allows reprogramming the USB chip.

AVR refers to the instruction set architecture used in a family of Atmel microcontrollers.  Several Arduinos  – Mega, Uno, Nano, Micro – use AVR chips.  Others, like the Zero and Due, instead use ATSAM3 chips, with an ARM instruction set architecture.


When I turn on the servo it spins on its own before going to the right position and start the sketch I can't get my head around this: when I turn the servo on it just spins on its own as if it's setting up, it goes to an angle superior to the one I want it to go. (Don't mind if it has to set up but it can't spin more than 20 degrees which is currently doing).

#include <Servo.h>

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

int degrees_of_motion = 20;
int servo_speed = 88;

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

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

What happens if you have a sketch such as the following? This uses the loop() function of the Arduino sketch to do one movement each time the loop() function is triggered.

#include <Servo.h>

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

int pos = 0;   // variable to store the servo position
int direc = 1; // direction and amount of position iteration, + to increment, - to decrement

int degrees_of_motion = 20;
int servo_speed = 88;

void setup() {
  myservo.attach(3);  // attaches the servo on pin 3 to the servo object
  pos = 0;            // start off with zero degrees.
  direc = 1;          // start off incrementing the angle by 1
}

void loop() {
  if (direc > 0 && pos > degrees_of_motion) {
    direc *= -1;       // change the direction of iteration, keep amount
    pos = degrees_of_motion;
  }
  if (direc < 0 && pos < - degrees_of_motion) {
    direc *= -1;       // change the direction of iteration, keep amount
    pos = - degrees_of_motion;
  }

  myservo.write(pos);    // tell servo to go to position in variable 'pos'
  pos += direc;          // increment/decrement the position
  delay(servo_speed);    // waits 15ms for the servo to reach the position
}


Arduino Uno suddenly not recognized in Windows 8.1 (code 43) I had my Arduino Uno connected to an external 12 V supply for 2-3 hours as I was working on other parts of my project. Suddenly the voltage from pin 9 which I was monitoring in the oscillator dropped down to 0 approximately.

I went on removing the external supply. The board was very very hot. I then connected the USB to my laptop and I got an error 43 (Windows did not allow the device to connect because it was reporting problems). I can't load any program of course. The 5 V pin works but it outputs a voltage lower than usual (at about 3.9 V). When I connect the external supply the 5 V pin outputs full voltage.

Any idea? Any fix?

Something is shorted out.

When you connect via USB, the USB port cannot supply enough current because of the short. The output drops to 3.9V and the USB port on your computer reports an error, probably due to over current.

When you connect the external power supply, it has enough power to supply the short. The output remains at 5V.

You can think of power supplies as having a very small internal resistance (R_p), and the board as being a resistive load (R_b). This forms a voltage divider, but because R_b >> R_p the voltage seen by the board is basically the same as that of the power supply. With a short, R_b is often < R_p, and thus the voltage seen by the board is much lower than the power supply voltage.

The fix will depend on which component is getting hot. Plug in the external power supply and check which one it is. Note: The component will get hot enough to burn your finger after a few seconds. One way is to check one component at a time, disconnecting the power between each check. Start with the big ICs.

If either the Atmega328P or the smaller ATmega8u2 (?) are hot, they will have to be replaced.

Finally, boards don't short out by themselves. Something is wrong with your circuit or you may have placed the board down on some conductive surface. If you post you circuit we might be able to spot the problem.


Why do we use HX711 with load cell (Why do we need A to D conversion)? We generally amplify the signal from load cell but why there is need for A to D (analog to digital) conversion?

The HX711 is nothing more than a sensitive amplifier that takes the tiny signals from a load cell and amplifies them coupled with a high resolution ADC.
You can do without the HX711 but the signals are so tiny and the Arduino ADC so low resolution that the results are useless.
You can create your own amplifier with op-amps and use the internal ADC of the Arduino, and the results will be reasonable, though the resolution will suck.
You can use another high resolution ADC chip to increase your ADC resolution so you can measure more accurate weights.
Or... you can just do it all in the one chip with the HX711.


Connecting Nokia 106 to Arduino I was wondering if this can be done. I got a Nokia 106 and am trying to make it talk, but the audio jack doesn't seem to cooperate and the Fbus pins are right under the SIM slot, which is right under the battery. Any advice?

Added: It seems that it talks AT commands, since it is a GSM model, but I'm not 100% positive.

Here's the picture of the Nokia FBUS connector from your link:

And here's a (slightly dubious) method of connection from some random web page

which goes on to say

  The F-bus protocol uses 115,200bps so we can easily use the Arduino’s serial function to communication with the phone. All you need to is hook up the phones TX to the Arduino’s RX and then use a resistor divider (I choose 330 ohm resistors) to connect the Arduino’s TX to the phones RX as shown above.

That page goes on to show how to use an Arduino to get the phone to send SMS text messages.

Sources:

http://www.insidegadgets.com/2013/01/12/how-to-use-nokia-f-bus-to-send-an-sms-message/
http://forum.gsmhosting.com/vbb/f148/nokia-105-new-100-working-solution-1731398/


Arduino esp8266 some times data will not be sent to thingspeak.com I have made an arduino IOT that sends temperature data to thingspeak and works fine . Now I have two questions
1-  In spite of active wifi connection from esp8266 toward the web , but why sometimes that is random the sensor data will not be sent to thingspeak.com ?
2- I need an android app that monitors the wifi and shows the sensor data that is collected by arduino and sent via wifi by esp8266 toward android hot spot , is any app available for this purpose?
Thanks a lot

َAbout first question I found after AT command AT+CWJAP="network","password" it takes a while to have  active and ready wifi connection  , so I used a 30 seconds delay after this command and then send sensor data toward thingspeak.com ,  now  problem is solved .


FastLED: "Invalid pin specified" I have an Adafruit Trinket (5v, 16mhz, based off of the AtTiny85 chip), and am wishing to use it with a strip with 24 3 pin, individually addressable LEDs (WS2812B). When I try to compile my code, I get this error:  static_assert(validpin(), "Invalid pin specified"); I've tried using different pins, but of them are seeming to work. What can I do to fix this issue? Here's my current code:

#include <FastLED.h>
#define LEDCOUNT 24
#define DATAPIN 0

CRGB leds[LEDCOUNT];

void setup() {
  FastLED.addLeds<WS2812B, LEDCOUNT>(leds, LEDCOUNT);
}

void loop() {
  leds[0] = CRGB::Red;
  FastLED.show();
  delay(30);
}

I think what @IgnacioVazquez-Abrams is getting at is:

void setup() {
  FastLED.addLeds<WS2812B, LEDCOUNT>(leds, LEDCOUNT);
}

Has LEDCOUNT showing up for both the number of LEDs and the data pin identifier.

Try:

void setup() {
  FastLED.addLeds<WS2812B, DATAPIN, GRB>(leds, LEDCOUNT);
}

This puts DATAPIN in the right place, and also adds the color order typical for WS2812B, GRB


Assigning an empty array row to reference int colors[][3] = {
  { 255, 0, 0 },
  { 0, 255, 0 },
  { 0, 0, 255 },
  { 253, 7, 210 }
};
int (*EXCLUSIVE_COLOR)[3];

I have a two-dimensional array to store some color values.
I have a 2nd array, which I am using to assign an "EXCLUSIVE_COLOR" from the first colors array.

What is the best method to assign a null or empty value to the "EXCLUSIVE_COLOR" array to be used upon initialization and when the "EXCLUSIVE_COLOR" is unset?

Initially I tried just assigning a default value to the array upon initialization:

int (*EXCLUSIVE_COLOR)[3] = {0,0,0};
//Produces an error: scalar object ‘EXCLUSIVE_COLOR’ requires one element in initializer

int (*EXCLUSIVE_COLOR)[3] = {0};
//assigns non-zero values to all three elements

I know that I can add a "dummy" record to the colors array to reference, when there isn't an "EXCLUSIVE_COLOR" set.

int colors[][3] = {
  { 255, 0, 0 },
  { 0, 255, 0 },
  { 0, 0, 255 },
  { 253, 7, 210 },

  { 0, 0, 0, }   //dummy record
};
int (*EXCLUSIVE_COLOR)[3] = &colors[4];

However I wanted to know if there was a cleaner way to be able to assign an empty value to reference when a color is not set, and when the array is initialized.

If you're using a pointer then there's no limit to what that pointer can point to.

The way I see it you have two sensible choices:

Point to a default value

This doesn't have to be in your array. It can be anything that is an int[3], since that is what your array consists of.

int[3] nothing = {0, 0, 0};

EXCLUSIVE_COLOR = nothing;

This means that it's actually pointing to something valid, in this case it's actually (I assume) the colour black.  That can make it easy to deal with, since EXCLUSIVE_COLOR[0] will be a valid value.

Point to nothing

You can point your pointer to NULL and it will be pointing to "nothing". This means that EXCLUSIVE_COLOR[0] is no longer valid, which can make handling it somewhat harder. However it does allow you to distinguish between "nothing" and "black", unlike option 1.

For example:

EXCLUSIVE_COLOR = colors[2]; // {0, 0, 255}
...
EXCLUSIVE_COLOR = NULL; // Not pointing anywhere

To test if it's pointing somewhere you can simply use if:

if (EXCLUSIVE_COLOR) {
   // you have a valid entry
}


Dragino lg01-p problem with serial monitor i have a dragino lg01-p lora gateway to which i successfully communivate through lora with an arduino and i can program it through network as expected and seen in its manual with the demo client-server code. However, when i try to open the serial monitor on the side of the dragino, i get this:
Unable to connect: retrying (1)...
Unable to connect: retrying (2)...
Unable to connect: retrying (3)...
Unable to connect: retrying (4)...
Unable to connect: is the sketch using the bridge?
I need to have the serial communication cause i made a little app in C# which gets the data from a COM port. I also tried with Console instead of serial, but still didn't get any results back. This is the code, exactly as is in the examples no the manual
#include <SPI.h>
#include <RH_RF95.h>

// Singleton instance of the radio driver
RH_RF95 rf95;

int led = A2;
float frequency = 868.0;

void setup()
{
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  while (!Serial) ; // Wait for serial port to be available
  Serial.println("Start Sketch");
  if (!rf95.init())
    Serial.println("init failed");
  // Setup ISM frequency
  rf95.setFrequency(frequency);
  // Setup Power,dBm
  rf95.setTxPower(13);
  // Defaults BW Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on
  Serial.print("Listening on frequency: ");
  Serial.println(frequency);
}

void loop()
{
  if (rf95.available())
  {
    // Should be a message for us now
    uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
    uint8_t len = sizeof(buf);
    if (rf95.recv(buf, &len))
    {
      digitalWrite(led, HIGH);
      RH_RF95::printBuffer("request: ", buf, len);
      Serial.print("got request: ");
      Serial.println((char*)buf);
      Serial.print("RSSI: ");
      Serial.println(rf95.lastRssi(), DEC);

      // Send a reply
      uint8_t data[] = "And hello back to you";
      rf95.send(data, sizeof(data));
      rf95.waitPacketSent();
      Serial.println("Sent a reply");
      digitalWrite(led, LOW);
    }
    else
    {
      Serial.println("recv failed");
    }
  }
}

Found it so i will share my problem here to help someone else!
Apparently Bridge funcions work better for this device if you include Process.h rather than Bridge.h.


Fritzing part repositry - GY-30 There is no GY-30 light sensor part design in the standard Fritzing repository.

Is there an official alternative part repository containing Fritzing fzpz file for this sensor?  Does it go by any other name or part code?

This part also goes by the name BH1750.  And that is available in the Fritzing  parts library.


Read two HX711 load cell amps I need to read two values from hx711 load cells connected to strain guages. Ive found the code below that reads one guage, but being self taught and with little experience I have no idea how to adapt it to work with two, is anyone able to help?
I need two individual readings not a combined one
Thanks in advance, and credit to sparkfun who wrote this code.
#include "HX711.h"

#define calibration_factor -7050.0 //This value is obtained using the SparkFun_HX711_Calibration sketch

#define DOUT  3
#define CLK  2

HX711 scale;

void setup() {
  Serial.begin(9600);
  Serial.println("HX711 scale demo");

  scale.begin(DOUT, CLK);
  scale.set_scale(calibration_factor); //This value is obtained by using the SparkFun_HX711_Calibration sketch
  scale.tare(); //Assuming there is no weight on the scale at start up, reset the scale to 0

  Serial.println("Readings:");
}

void loop() {
  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 1); //scale.get_units() returns a float
  Serial.print(" lbs"); //You can change this to kg but you'll need to refactor the calibration_factor
  Serial.println();
}

The line:
HX711 scale;

is called the "instantiation of the object". It creates a new object called scale which is an instance of the HX711 class. It is this "object" that is your interface to the HX711 physical device.
To use two of them you first need to have two objects - one for each HX711. You can name them whatever you like.  For example:
HX711 scale1;
HX711 scale2;

The line:
scale.begin(DOUT, CLK);

is where it tells the HX711 object which pins the HX711 chip is connected to. In this case DOUT and CLK which you have defined as 3 and 2 respectively.  You could just as well have written:
scale.begin(3, 2);

Each object has to be "begun", so you would need a begin for each object you instantiate:
scale1.begin(3, 2); // DOUT = 3, CLK = 2
scale2.begin(5, 4); // DOUT = 5, CLK = 4

Now for every operation that you did on scale you would instead do on your two new objects:
scale1.set_scale(calibration_factor);
scale2.set_scale(calibration_factor);

etc.
And when you want to take a measurement you just select which object to read from:
Serial.print(scale1.get_units(), 1);

or
Serial.print(scale2.get_units(), 1);

You can add a third by creating and using scale3 in exactly the same way as scale1 and scale2.


Read analog port set as output I have a PWM analog port that is outputting a frequency, is it possible to do an analogRead on the same pin and get a correct value? If so, will reading that port disrupt the freq output on the pin? This is being done on a Teensy 3.2 device. My goal is to output the freq visually on an OLED. Tnx.

No, it's not possible.

PWM is not actually analog - it's digital, but switching on and off at a high speed.

If the pin were capable of reading an analog value at the same time as outputting a PWM waveform (which I highly doubt...) all you would get is alternating 0 and 1023 values (or whatever range the Teensy reads in).


Arduino IDE 1.8.6 not starting. My Arduino IDE is not getting started. It just crashes before opening up. I don't know what the problem is. It was working well enough before without any issues.

This is what I see after running the arduino_debug.exe in the command line

Note: I added a library (DHT) to work with my humidity and temperature sensor and since after then, this issue comes up. I tried to reinstall it like more than 7 times, but the issue still persists.

Please help me with it. Thanks.

The cause of the problem is that you have a corrupted library index file. The solution is to delete the file, which will force the Arduino IDE to download a (hopefully) uncorrupted fresh version from the Internet:

Open the C:\Users\JK\AppData\Local\Arduino15 folder
Delete the file library_index.json
Try starting the Arduino IDE again

For anyone encountering this problem who is using an operating system other than Windows, the location of library_index.json is different:

On Linux:

/home/{username}/.arduino15 (a.k.a. ~/.arduino15)

On macOS:

/Users/{username}/Library/Arduino15

If using the Arduino IDE in portable mode:

{Arduino IDE installation folder}/portable

The issue of a corrupted library index file preventing the Arduino IDE from starting has been reported to the Arduino developers and they are already working on a fix:

https://github.com/arduino/Arduino/issues/7937


Insert Variables In AT commandes I'am trying to apply USSD operation with variable codes, for example this piece of code return my account balance:

             gsm.SimpleWriteln("AT+CUSD=1,\"*100#\"");

i want to change "*100#" to variable so gsm.SimpleWrite uses what the variable contains. I want to find how to make it work like this:

             gsm.SimpleWriteln("AT+CUSD=1,\"Variable\"");

EDIT: here is my code to give you a better view. it return balance in serial monitor.

#include "SIM900.h"

  void setup()
    {
   Serial.begin(9600);
    Serial.println("GSM Shield testing.");
       if (gsm.begin(9600))
            Serial.println("\nstatus=READY");
      else Serial.println("\nstatus=IDLE");

         gsm.SimpleWriteln("AT+CUSD=1,\"*100#\"");
      delay(10000);
             char msg[200];
             gsm.read(msg, 200);
            Serial.print("resp: ");
            Serial.println(msg);
 }
    void loop()
     {

    }

I cannot find which "SIM900.h" library you are using - none of the ones I found have "SimpleWriteln" in them, so this is pure assumption about what functions and overloads may be available.

Just split your string into chunks, like you would with any serial device:

gsm.SimpleWrite("AT+CUSD=1,\"");
gsm.SimpleWrite(command);
gsm.SimpleWriteln("\"");

Where command is a suitable container for your data - say const char *.


My Arduino keeps telling me the button is being pushed My code is simple simple for the button.

There is no reason why this shouldn't work... I think. I honestly have no clue what's wrong.

Output:

Code:

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

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

int led = 13;
int led2 = 12;

Bounce debouncer1 = Bounce();

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

int buzzer = 10;

Servo LockServo;

int ServoPos = 0;

void setup()
{
  debouncer1.attach(buttonPin);
  debouncer1.interval(5); // interval in ms

  pinMode(buzzer, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP); // Push Button as INPUT wiith pullup
  buttonState = digitalRead(buttonPin);
  LockServo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  Serial.println("Approximate your card to the reader...");
  Serial.println();
  pinMode(led, OUTPUT);
}

void loop()
{
  debouncer1.update();
  buttonState = debouncer1.read();
  if (buttonState == HIGH) {
    Serial.println("Button Pushed");
    // turn LED on:
    digitalWrite(led, HIGH);
    ServoPos = 0;
    LockServo.write(ServoPos);
  }
  else {
    digitalWrite(led, LOW);
    ServoPos = 180;
    LockServo.write(ServoPos);
  }

  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "20 96 2E A5") //change here the UID of the card/cards that you want to give access
  {
    Serial.println("Authorized access");
    Serial.println();
    digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
    ServoPos = 0;
    LockServo.write(ServoPos);
    tone(buzzer, 20000);
    delay(500);
    noTone(buzzer);

    tone(buzzer, 15000);
    delay(500);
    noTone(buzzer);
    delay(15);
    delay(3000);
    digitalWrite(led, LOW);
    delay(3000);
    ServoPos = 180;
    LockServo.write(ServoPos);
  }
  else {
    Serial.println(" Access denied");
    tone(buzzer, 10000);
    delay(500);
    noTone(buzzer);

    tone(buzzer, 30000);
    delay(500);
    noTone(buzzer);
    digitalWrite(led2, HIGH);
    delay(3000);
    noTone(buzzer);
    digitalWrite(led2, LOW);
  }
}

When using a pull-up mode on an input pin, that means that when nothing is connected, the pin floats up to HIGH. The connected button should have one side connected to your input pin, and the other to GND, so that when you press the button, the input pin is pulled to GND (that is, LOW).

So your comparison to trigger on a button press should be if (buttonState == LOW)


WiFi module ESP8266 + Arduino Uno I'm trying to connect a WiFi module, ESP8266-01 to an Arduino Uno. But, as I've understood, this module will only work with 3.3 V. Since all of the data pins use 5 V, one of the solutions is to use a voltage regulator, such as LM2596.

My questions are:

Does anyone know if there already exists a tutorial that describes the way this WiFi module can be connected to an Arduino Uno?
For a simple server, would I need to use several voltage regulators (since there are quite many pins)?
Since Rx is the receiver, it would not need a voltage regulator because that pin can handle up to 5 volts?
Is there any need for an external power source, such as a cell?

Since all of the data pins use 5 V, one of the solutions is to use a voltage regulator, such as LM2596.

You do not want a voltage regulator you need a level shifter.

You can buy them cheaply or make them up with a transistor or MOSFET.

I gather the ESP8266 has a Tx (transmit) to the Arduino. You probably don't need to level-shift that, as the Arduino Uno will interpret 3V upwards as a HIGH. For the Rx (receive) from the Arduino you need to level-shift the data pin (possibly a voltage-divider might work) since the 5V from the Arduino needs to be converted down to 3.3V.

The ESP8266 Vcc and CH_PD can go to the Arduino 3.3V pin.

Disclaimer - I haven't done this, I am summarizing what I read on various web pages. Read some of the answers on the pages you get when you do a Google search for more details.

References

Voltage divider - Wikipedia
Level shifter - StackExchange
SparkFun Logic Level Converter - Bi-Directional
4-channel I2C-safe Bi-directional Logic Level Converter - Adafruit
Bi-directional level shifter for I²C-bus and other systems - PDF
ESP8266 Community Forum


Timer/Counter programming Arduino I'm trying to blink an LED on an ATMega328P (same MCU as Arduino I think..) using the internal timer but I'm stuck since it doesn't seem to light the LED at all....

#include <avr/io.h>
//#include <avr/delay.h>

void delay(void);

void delay_long(void);

int main(void) {

  DDRB = 0xFF;                   // port B is configured as output   DDRB : 0b11111111
  DDRB &= ~(1<<PB1);             // pin 1 of port B is configured as input  DDRB : 0b11111101
  PORTB = 0x00;                  // pins of port B are low (output) and with no pull-up resistor (input)
  PORTB |= (1<<PB0)|(1<<PB1);    // pin 0 is high (output) and pin 1 is pulled high (input)    PORTB : 0b00000011

  while(1) {
    PORTB &= ~(1<<PB0);
    delay();
    PORTB |= 1<<PB0;
    delay();
    PORTB = ~(1<<PB0);
    delay_long();
    PORTB = 1<<PB0;
    delay_long();
  }

  return 1;

}

void delay(void) {
  TCNT0 = 0x00;
  TCCR0B = 0x05;
  while ( (TIFR0 & TOV0) == 0 )
    ;
  TCCR0B = 0x00;
  TIFR0 |= 1<<TOV0;
}

void delay_long(void) {
  TCNT0 = 0x00;
  TCCR0B = 0x05;
  while ( (TIFR0 & TOV0) == 0 )
    ;
  TCCR0B = 0x00;
  TIFR0 |= 1<<TOV0;
  TCCR0B = 0x05;
  while ( (TIFR0 & TOV0) == 0 )
    ;
  TCCR0B = 0x00;
  TIFR0 |= 1<<TOV0;
}

if I remove the body of the event loop it lights up... so I think I must be missing something in the delay functions...

It seems that the offending line is:

while ( (TIFR0 & TOV0) == 0 )

TOV0 by itself equals 0, so the above loop will never end.

You should use:

 while ( (TIFR0 & (1<<TOV0)) == 0 )

instead.


Why does my sketch report too many button presses? I've been using a button to interact with a sketch (on my Uno), and it's mostly working fine. However, sometimes it seems to be detecting multiple presses when it's only pressed once.

It's a small circuit-mounted momentary button, which is normally open. It's connected from +5V directly to an input pin. I've also added a 10K pull-down resistor on the pin to make sure the input isn't left floating.

Here's a test sketch I've been using, which reports the number of presses to the serial monitor:

int oldState = LOW;
int numPresses = 0;

void setup()
{
    pinMode(5, INPUT);
    Serial.begin(9600);
}

void loop()
{
    const int newState = digitalRead(5);

    if (newState != oldState) {
        if (newState == HIGH) Serial.println(++numPresses);
        oldState = newState;
    }
}

Sometimes when I press the button once, the serial monitor shows two presses in a row. It sometimes even reports a press when I release the button.

Is it possible to fix this? Or do I just have a faulty button or pin or something?

Contact Bounce

This is known as contact bounce and happens when the metal contacts in the button or switch bounce against each other when you push it. The microcontroller is fast enough to pick up these bounces and, as far as it's concerned, you're toggling the switch many times in as much as 10 milliseconds of time.

Different switches and buttons will have a different amount of contact bounce, and even one switch will behave differently between two presses.

Here's a button press captured on a scope (image from Maxim):

At 2ms/div we don't see a stable signal until 6ms after initial contact!

Solutions

Add a delay

The absolute simplest solution is to introduce a short delay after you read the button input. This will prevent the code from picking up any bounces and when it resumes, the signal should be stable.

if (digitalRead(A3) == 0) {
    // do something here
    delay(500);
}

In the example above, I delay 500ms after reading the state of the pin. The button is normally high so when I press it down, the state of the pin goes to logic 0. I pick that up in the code and do something and then wait at least 500ms before continuing.

Obviously, this code will just halt for half a second every time you push a button, which may or may not be acceptable in your application. You can decrease the amount of delay depending on the contact bounce time of your switch, too, but I play it safe here.

Ignore button presses too close to each other

Similar to the solution above but instead of adding a hard delay, you use the millis() function to keep track of when the last time the switch was triggered. Every time you see a switch trigger, you compare against the time and, if not enough time has elapsed (say like 500ms in my previous example), you ignore it.

This solves the problem of having to use delay() in your code.

Switch debouncer IC

There are things like the MAX6816 which is an IC that you put in between your switch and microcontroller input. It will denounce the signal for you. At a price of $1.62 @1k you'll probably never use this.

Other

There are many solutions to this problem... I always do it in software, but some others include using a latch or capacitor.

Debounce Code – one post to rule them all


analogRead always returns 1023 - Arduino Mega 2560 I have connected an FSR (Force Sensitive Resistor) to  as per image(edited name for avoiding mismatch). When I measure the voltage b/w two pins of fsr, voltage changing as per pressure applied. But analogRead always returns 1023. But my another Mega works good with same code and configurations. Can someone guide me to correct it. Thanks in advance.

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

void loop() {
  int num1 = analogRead(A15);
  Serial.println(num1);
  delay(1500);
}

I had a similar problem when I ported my code from an Arduino Due to an Arduino Mega. I was able to solve this problem by adding the following call in the setup function.

analogReference(DEFAULT);

It seems that in some other Arduinos, the analog reference will be selected automatically, but at least the Arduino Mega needs it.


4 channel Remote Control I'm trying to make a 4 channel RC using Arduino and nrf24L01 module.
I already know how to deal with this module, but the question is "What does 4 channel mean ?", and how to make it supports 4 channel ?

4 channel means having the ability to send 4 individual values (maybe speeds?) at once.

Since the nRF24L01+ is a packet based system it is as simple as sending the different "channels" as different bytes (or groups of bytes if more than 0-255 or -128 to +127 is needed).

For instance, if you want 4 channels that can represent 0-255 then you need 4 bytes, and so you can set both sender and receiver to have a packet size of 4 bytes (for efficiency) and send a packet made up of the 4 channel values.

If you want to represent numbers bigger than that then you need to split the variable into bytes (two bytes for an int, 4 for a long) or create a struct to represent your packet of data. Of course you then need the sender and receiver to be set to a packet size at least big enough to contain the data, and both ends must agree on the packet size.


Temperature and Humidity Sensor TinyShield (No device found on com5) Hi i have recently started working on a Temperature and Humidity Sensor TinyShield (ASD2511-R-T) and faced the issue as shown in the image below: No device found on com5.

I have followed the tutorial as shown in the TinyShield webpage and worked through the steps. 1) Installed the Arduino IDE, 2) Installed the Si7021 Arduino Library, 3)Download the .zip file of the example program and open it in the Arduino IDE.

This is the following example code provided by the tutorial.

/*
  TinyCircuits Si7020 Temperature and Humidity Sensor TinyShield Example Sketch

  This demo shows the bare minimum to read temperature and humidity data from
  the Si7020 sensor using the Si7020 library written by Marcus Sorensen.

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

  Written 20 March 2016
  By Ben Rose
  Modified 07 January 2019
  By Hunter Hykes

  https://TinyCircuits.com
*/

#include <Wire.h>
#include <SI7021.h>

SI7021 sensor;

void setup()
{
  Serial.begin(115200);
  Wire.begin();
  Serial.print("Initializing sensor... ");
  if(!sensor.begin()){
    Serial.println("Sensor not found!");
    while(true);
  }
  Serial.println("Success!");
}

void loop()
{
  int celcius=sensor.getCelsiusHundredths()/100;
  int relativeHumidity=sensor.getHumidityPercent();
  Serial.print(celcius);
  Serial.print(" deg Celsius\t");
  Serial.print(relativeHumidity);
  Serial.println("% relative humidity");

  delay(500);
}

However, when I proceed to upload the program, the following error had occurred. This is the first time i am working on a TinyShield product.

Any help is appreciated! Thanks!

Do let me know if i need to provide any further information.

The options for COM 5 the only one avaliable.

The below was the issue, i was using the wrong broad and processor.

Thanks for the help!


String class summation disappears the right operand I intend to create a function to jsify sensors' content and save it on a SD-card or send through a http client. Except for the Serial.println's, the function is transcripted below.

String jsonificar(vector<vector<String>> sujeito){
  String json_txt = String(""), chave, valor;
  String chave_str, valor_str;

  json_txt+=String("{");
  for(unsigned int i = 0; i<sujeito.size(); i++){
    if(sujeito[i].size() != 2){
        Serial.println("Cada conteudo deve conter 2 textos!");
    }
    else{
        chave = sujeito[i][0];
        valor = sujeito[i][1];
        Serial.println(chave);
        Serial.println(valor);
        Serial.println(json_txt);
        json_txt += "\\\"";
        Serial.println(json_txt);
        json_txt += chave;
        Serial.println(json_txt);
        json_txt += "\\\"";
        Serial.println(json_txt);
        json_txt += ":";
        Serial.println(json_txt);
        json_txt += "\\\"";
        Serial.println(json_txt);
        json_txt += valor;
        Serial.println(json_txt);
        json_txt += "\\\"";
        Serial.println(json_txt);

        if(i != sujeito.size() - 1){
          json_txt += String(",");
        }
    }
  }

  json_txt+="}";
  Serial.println(json_txt);

  return json_txt;
}

The output on serial follows:

Output:

Chave1
Valor1
{
{\"
{\"Chave1
{\"Chave1\"
{\"Chave1\":
{\"Chave1\":\"
{\"Chave1\":\"Valor1
{\"Chave1\":\"Valor1\"
Chave2
Valor2
{\"Chave1\":\"Valor1\",
{\"Chave1\":\"Valor1\",\"
{\"Chave1\":\"Valor1\",\"    <===
{\"Chave1\":\"Valor1\",\"\"
{\"Chave1\":\"Valor1\",\"\": <===
{\"Chave1\":\"Valor1\",\"\": <===
{\"Chave1\":\"Valor1\",\"\": <===
{\"Chave1\":\"Valor1\",\"\": <===
{\"Chave1\":\"Valor1\",\"\":}

The arrows show the spots where the logs are different from expected: the keys and values provided are "Chave1", "Valor1", "Chave2", "Valor2". So, the key-value should be "Chave2":"Valor2". Would you have a grasp of this behaviour? I look forward for the answer!

Your "disappearing string" has the following cause: Out-of-Memory.

You are constructing lots of String objects in your code and are concatinating to one. That uses memory on the heap for each String (and realloc() when the String memory must be expanded).

Consider the following test sketch which includes your code but also adds a memory leak by 150 bytes in each iteration:

#include <Arduino.h>
#include <ArduinoSTL.h>
using namespace std;

extern unsigned int __heap_start;
extern void *__brkval;

/*
 * The free list structure as maintained by the
 * avr-libc memory allocation routines.
 */
struct __freelist {
    size_t sz;
    struct __freelist *nx;
};

/* The head of the free list structure */
extern struct __freelist *__flp;

/* Calculates the size of the free list */
int freeListSize() {
    struct __freelist* current;
    int total = 0;
    for (current = __flp; current; current = current->nx) {
        total += 2; /* Add two bytes for the memory block's header  */
        total += (int) current->sz;
    }
    return total;
}

int freeMemory() {
    int free_memory;
    if ((int) __brkval == 0) {
        free_memory = ((int) &free_memory) - ((int) &__heap_start);
    } else {
        free_memory = ((int) &free_memory) - ((int) __brkval);
        free_memory += freeListSize();
    }
    return free_memory;
}

String jsonificar(vector<vector<String>> sujeito) {
    String json_txt = String(""), chave, valor;
    String chave_str, valor_str;

    json_txt += String("{");
    for (unsigned int i = 0; i < sujeito.size(); i++) {
        if (sujeito[i].size() != 2) {
            Serial.println("Cada conteudo deve conter 2 textos!");
        } else {
            chave = sujeito[i][0];
            valor = sujeito[i][1];
            Serial.println(chave);
            Serial.println(valor);
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += chave;
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += ":";
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += valor;
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);

            if (i != sujeito.size() - 1) {
                json_txt += String(",");
            }
        }
    }

    json_txt += "}";
    Serial.println(json_txt);

    return json_txt;
}

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

String myStr = "";

void loop(void) {

    Serial.print(F("Free Memory:"));
    Serial.println(freeMemory());

    //force a memory leak by allocating appending to a global String
    myStr +=
            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

    vector<vector<String>> v =
            { { "Chave1", "Valor1" }, { "Chave2", "Valor2" }, };

    jsonificar(v);
    delay(1000);
}

From the output we can see the exact point where we have enough memory and the result is correct, and where we don't have enough memory and the string just "disappears" because there was not enough memory to allocate it:

Free Memory:911
Chave1
Valor1
{
{\"
{\"Chave1
{\"Chave1\"
{\"Chave1\":
{\"Chave1\":\"
{\"Chave1\":\"Valor1
{\"Chave1\":\"Valor1\"
Chave2
Valor2
{\"Chave1\":\"Valor1\",
{\"Chave1\":\"Valor1\",\"
{\"Chave1\":\"Valor1\",\"Chave2
{\"Chave1\":\"Valor1\",\"Chave2\"
{\"Chave1\":\"Valor1\",\"Chave2\":
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2
{\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2\"}
Free Memory:761
Chave1
Valor1
{
{\"
{\"Chave1
{\"Chave1\"
{\"Chave1\":
{\"Chave1\":\"
{\"Chave1\":\"Valor1
{\"Chave1\":\"Valor1\"
Chave2
Valor2
{\"Chave1\":\"Valor1\",
{\"Chave1\":\"Valor1\",\"
{\"Chave1\":\"Valor1\",\"Chave2
{\"Chave1\":\"Valor1\",\"Chave2\"
{\"Chave1\":\"Valor1\",\"Chave2\":
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"


Arduino join multiple strings and numbers and then seperate them OK, I'm working on a remote controlled robot. Both the robot and the remote use Arduino with a Bluetooth shield. The Bluetooth is working and I need to send something similar to this over Bluetooth:

X:1026,Y:1026,Button:1

There may be more buttons added and X,Y can be between 1026 and 0. How can I build that string from:

xPosition = 1026;
 yPosition = 1026;
 buttonState = 0;

I also need to be able to separate that string back into variables on the 2nd Arduino.

EDIT: I have seen other questions similar to this but they involved Serial. I am using Bluetooth.

EDIT AGAIN: I am sending the data over Bluetooth with the BlueToothSerial.print command from the SoftwareSerial.h library. (BlueToothSerial is SoftwareSerial BlueToothSerial(RxD,TxD);)

To make the string you can:

char outstring[30];
sprintf(outstring, "X:%d,Y:%d,Button:%d", xPosition, yPosition, buttonState);

Be sure to make the outstring big enough to store it all.

That is, of course, if you actually need to have the whole thing in one string all the time.  You haven't said how you are sending it (yes, I know, bluetooth, but there is bluetooth and there is bluetooth, and there are different ways of it working.)

Splitting a string like that can be done with strtok() then looking for the location of the colon in each returned token. Or, depending on how the string data actually arrives, could be parsed on a character-by-character basis, which would be better. Again, because you haven't told us how the data is actually being transferred it's impossible to elaborate on that.


Arduino Bluetooth Range Control I am creating a project that uses Bluetooth, But unfortunately it requires some kind of control of the range. I was thinking a potentiometer controlling the power going to the transmitters antenna. But I have no clue how I would program this. Can anyone help me out or point me in the right direction? Thanks

EDIT
Okay I am making this because I am designing a sensor that tells if you are in a room. For example when you leave the room the Bluetooth single is no longer in range then it notifies the arduino. I am not sure if you can do this but I cant see why not.

This should not be the solution to your problem which is btw. not exactly clear. Do you want to prevent people outside of this range to connect, or do you have some sort of interference problem (in this case it might be legitimate)?

Unauthorized access should not be controlled by range because it depends not only on your sender antenna but also on the gain of the receiving device. Anyways, in the frequency bands and energy levels of a Bluetooth antenna a potentiometer will not work.

Implement access control beyond the pairing in your application.

There should be some fancy Bluetooth devices that allow for energy control. Especially, low-energy devices.


Transmitting Electrodes Signal to Breadboard Wireless I have recently made a DIY EEG from schematics and instructions I found online. I wanted to take the electrodes signal and transmit it wirelessly to the breadboard. According to the picture, the 2 electrodes wire (used for amplifying signals) would be attached to pin 2 and 3 on the AD620AN component, and the third electrodes would be attached to the ground of the breadboard. However, is there a way to transmit the information wirelessly to the AD620AN? I wanted the EEG to be wireless so that it is more practical to wear when performing activities, rather than having wires everywhere. The picture will show the final output of the breadboard going to a soundcard but mine is actually going to the analog input of the Arduino.
Thank you.

No. Certainly not. You are thinking completely backwards.  It is necessary for the electrodes to go directly into that circuit since that circuit amplifies the tiny signals from the electrodes to make them readable.

You should instead think about shrinking your design to the stage where it becomes possible to make the Arduino be wireless and send the data somewhere else.


Disable the Amplifier during the flashing ESP8266 I use ESP-12 and Adafruit Mono Amplifier for playing audio. It works but It has one big issue. My circuit uses RxD to transfer audio (A+ connect to RxD), also ESP uses for flashing the chip. This causes horrible noise when it is programming the ESP8266 from the speaker. The good thing about this module is it has SD pin which can be used to turn it off.

Now the question is how I can connect this SD pin to disable the amplifier during the flashing procedure and also keep it off by default in normal mode and use something like digitalWrite() to turn it on manually in my application when it is needed. Thanks

SD is pulled up to VIN by a 10kΩ resistor. You will need to pull it down to ground with something "stronger" that 10kΩ - a 1kΩ resistor would probably do it.

Then you can drive the pin HIGH and override that 1kΩ resistance to enable the module.

You could also modify the module to remove the 10kΩ pull-up resistor (the one right by the VIN label which has 1002 printed on it) and use a weaker pull-down resistor (10kΩ would be good).


Is this a fake pulse sensor? A couple of days ago, I purchased a pulse sensor online for a project. Before actually doing anything with it, I wanted to capture and view its analogue waveform output. One while placing my finger on it and one when in the default state, so that I can see the trend or difference in the two waveforms. But when I captured the output, it seems like there is not much difference. Just some random noise I guess. Also, I checked the company website who may have made this one and it all looks good to me.

The image below shows the waveform captured when no finger is placed on the sensor.

The image below shows the waveform captured when my index finger is placed on the sensor.

This is my setup for the sensor for measuring pulses.

This image shows the face of the sensor.

I need some insights from folks here regarding this sensor. Is it showing some junk output? or my understanding is wrong and there's a better way to figure this out/ work with this sensor.

The second trace looks like a pulse to me. With that kind of sensor you don't get the PQRST traces of an ECG - just a slight bump when you get a pulse.


Purpose of extra holes for pins or Arduino clone I bought this Arduino clone recently and it has lot of extra holes for pins, but some of them I don't know what they do. There was no instruction manual that came with it. Here's a picture of it, I added a red rectangle around the ones I don't know. (4 pins with X1, SCL/SDA, AREF and blank pin in the bottom)

I thought I could use the pins SCL SDA 5V GND with my I2C LCD Display because the names of the pins are the same on it. Could it work? Usually I use analog pins to connect the display, does that mean that by using it some analog pins will be used indirectly? I didn't try connecting it because I don't want it to break.

What do these pins do?

It's what they say they are.

SDA/SCL are I2C - what used to be A4/A5 on the old footprint. On the '328 based boards those are directly linked to the A4/A5 pins.

The blank pin isn't used. The 5V next to it is actually mislabelled and should be labelled "IOREF".

AREF has been there since the very first Arduino boards.

It's the standard "R3" Uno footprint, plus some extra breakouts for the I2C in different forms (probably to go with specific I2C devices they also sell).

All of that is on the Uno's product page if you'd care to read it some time...

The ones by the cheap Chinese USB interface chip will be something to do with that. Maybe RTS/CTS broken out on a header. You can ignore those - they are of no interest at all. In fact, just looking in their direction has a good chance of breaking the USB interface chip. Stay well away.


Arduino Uno to drive 2 unipolar stepper motors I need to use two stepper motors to move microscope positioning knobs in the X/Y direction. The stepper motors I have are unipolar and are 6V rated (I think).

I know it's possible to drive a unipolar stepper motor via a ULN2003 using an Arduino Uno. I know I can wire it using the 2-wire or 4-wire method.

But my questions are:

Is it possible to drive 2 of them? What are the modifications I will need to make to the circuit? Will this harm my Arduino? Do I need a stepper motor shield?

No problem. Just use two ULN2003 chips, one for each stepper.

No need for a motor/stepper shield on these unipolar steppers.

It will not harm the arduino (if wired correctly).


Detecting mutual contact between balls Is there a simple way to rig two balls in a way that lets you know if they are touching?

For example, here's a bad idea. Put a free-to-move magnet inside of each ball. When the balls get close, the magnets snap together. Use a magnetic sensor within each ball to tell the direction of the magnet. Use an accelerometer to tell the direction of gravity. When the gravity direction differs from the magnet direction, the balls are touching.

I don't need to know the direction of the contact (that would be ideal, but I don't need it). It should work over the whole surface. I would like to have more than two balls and be able to tell which two are touching. I can make the balls however I want.

(Even very basic advice would be quite helpful. I'm not familiar at all with hardware projects or what kinds of sensors are available or how to combine the available pieces into some desired thing. That includes advice like "this is probably too hard".)

Option 1

Seems you say you can make the balls out of whatever you want, I would suggest the spheres be made of a metal and then you can either suspend them by wire spot welded or soldered onto the balls. Then what you do is you connect all the balls to inputs of an Arduino ( this is if you are doing this with one). Then connect all inputs to pull-up resistors.

Then to read if a ball is touching a neighbour you start with ball n and set it as an output and use digitalWrite(n,LOW);  and then poll all the other balls as inputs to see which one reads LOW/0V and then record that in an array, you the move onto ball n+1 and scan the rest of the balls. There is also no need to read the previous ball to n+1 as if it did not register a touch, then it won't register with the next ball.

Then at the end you reset everything and start at the beginning again. Using the data how you wish at the end.

Below code is just to show, not tested.

for(int n =0; n < total_N; n++){
      pinMode(n, OUTPUT);

  for(int i = 0; i < total_inputs; i++){
          if(!(digitalRead(n)))// ball is touching
   {

         myArray[i] = 1;// store a point in the list, replace with a way you want
    }
    else myArray[i] = 0;
}
     pinMode(n, INPUT);
}

Option 2 (probably to much to go wrong)

You could use material that will allow IR rays to pass through and make you balls with that. Then in each ball is have a IR transmitter and a IR receiver, making a transceiver basically and then have each ball echo a specific ID and let the other balls pick it up.

To solve the issue that IR travels a good distance you will need to limit the power/voltage/current to the IR transmitter(LED) so that they only work within a certain range.

Option 3

You could place reed switches or hall effect sensors in each ball, with a magnet. Place a niece of metal behind the sensor so that the magnet is drawn to it. The only issue with this is that either the magnet in each ball will not only affect its neighbour but also itself. So they will need to be spaced and also the right strength of magnet.

Option 4

A combination of option 2 and 3 would be to surround a IR receiver setup with a piece of metal disk(like a washer) and also a reed switch or hall effect sensor, and then have a ball with a magnet and a IR transmitter by a magnet, so that when the two are pulled together the transmitter and receiver match up in the same view and are able to tell them that they are connected, you would thus have each ball with a set, one to receive placed on one side and another on the opposite side to transmit.


How can I get two Arduinos to "talk" to each other? I'm pretty new to this whole thing so please excuse my lack of familiarity with terminology.

I'm looking to build two "buzzers" of sorts. One will live on the ground floor and the other will live on the fourth floor. There is wireless internet as well as wired internet available to connect the two.

This is the basic idea. I might put more frills in later. Both buzzers have one button and one LED. I want it so that once a buzzer's button is pressed, the LED lights on both buzzers will light up. Then, only when buzzer two's button is pressed, will the LED lights on both buzzers turn off.

I'm pretty tied up on the two Arduinos communicating with each other. Is it possible to do something like that?

Wired

Communication speed is not a factor - you only have to transmit an on/off signal. The simplest method would be to run a 4-wire cable, like a telephone cable, between the two.

The wires would be

GND
5V (maybe)
Ground floor output -> fourth floor input
Fourth floor output -> ground floor input

The steps are

Both wire 3 and 4 start LOW When ground floor button is pressed, ground floor led goes on, wire 3 is set HIGH.
Fourth floor is monitoring wire 3, when it goes HIGH, fourth floor led goes on, and    wire 4 is set HIGH
Ground floor is monitoring wire 4, when it goes HIGH, ground floor led goes off, and wire 3 is set LOW
Fourth floor is monitoring wire 3, when it goes LOW, fourth floor led goes off,    and wire 4 is set LOW
Ground floor is monitoring wire 4, when it    goes LOW, it begins waiting for a button press again.

Wire 2 can be used for 5V (or 3.3V depending on the Arduino) so that one of the devices can be powered off the other.

Wireless

The other option is to attach an RF transceiver to each Arduino, something like this would be good as it has 100m line-of-site range which you might need to get through 4 floors of concrete.

Learning

Start off with the simple wired method shown above. When it is working, connect wire 3 and 4 into the RX and TX pins and try to communicate using the serial port. Finally, move on to the wireless transceivers.


Arduino Ethernet Shield 2: How can I automatically determine the MAC Address? I'm using an Arduino Mega.
I know that Ethernet Shield 2's come with a sticker with the MAC Address printed on it. This would imply to me that this address is hardcoded into the shield. Is there any way to recover the MAC without manually entering it in the sketch?
Thanks!

No, the W5500 chip does not have a mac address. You can give it any mac address that you want. The router might not like some mac addresses though.

There are online mac address generators.

The sticker with the mac address is an extra service. It is unique number. But it is just a number on a sticker, it is not related to that specific shield.

Often the mac address DEADBEEFFEED was used. But when two different Arduino boards use the same mac address, the router thinks it is the same device. When there are two devices with the same mac address at the same time connected, that is for sure a way to mess up the router.


Defining an NFC tag as NDEF using the Arduino Uno and the PN532 NFC module I bought a bunch of blank Mifare Classic NFC cards and I'd like to write NDEF records to them using my Arduino Uno. When I read them using my Uno and a PN532 NFC module using Don's NDEF library however, it tells me they're not NDEF formatted.

Is there any way to define my NFC tags as NDEF using just the PN532 module and an Arduino Uno? (My Android phone doesn't support NFC.)

I found the answer to my own question right after posting it, while going through the examples included in the library above:

The library contains an example named "FormatTag" which does exactly what I was looking for.


Arduino Serial Monitor I am currently trying to see the result of a query to a thingspeak field.
This works great when I just use a empty sketch and type the commands manually, but using the following sketch I cannot see the value of +IDP,0,1:1
This means, at field 1, the value 1 is stored. If 0 was stored, it would be +IDP,0,1:0
How it is possible to "ask" if "+IDP,0,1:0" exists at the serial message from the ESP8266? Serial.find does not work....

Here my sketch:

#include<stdlib.h>
#include <SoftwareSerial.h>

SoftwareSerial monitor(2,3); //rx tx
#define SSID "WLAN-0E0265"
#define PASS "2738564673200634"
int ledPin = 13;
String c;
void setup() {
  Serial.begin(9600);
  monitor.begin(9600);
  monitor.println("AT");
  delay(1000);
  monitor.println("AT+CIPMUX=1");
  delay(1000);
  monitor.println("AT+CWJAP=\"WLAN-0E0265\",\"2738564673200634\"");
  delay(5000);
  if(monitor.find("OK"))
    Serial.println("JAP worked");

  monitor.println("AT+CIPSTART=0,\"TCP\",\"api.thingspeak.com\",80");
  delay(2000);
  if(monitor.find("OK"))
    Serial.println("CIPSTART worked");
  monitor.println("AT+CIPSEND=0,110");
  delay(2000);
  if(monitor.find(">"))
    Serial.println("CIPSEND worked");
  monitor.print("GET https://api.thingspeak.com/channels/54209/fields/1/last \r\n");
  delay(10000);
  monitor.println("GET https://api.thingspeak.com/channels/54209/fields/1/last");
  delay(2000);
  String readString;
  ledPin = 13;
  //++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//SEARCH FOR THE :0 or :1                           <-- Here is the problem, rest works fine
  if(Serial.find(":0")){
 //turn pin off
}
  if(Serial.find(":1")){
 //turn pin on
}

}

void loop(){

}

The problem is that you can't use serial's find function to look for one thing or another.  It is a greedy function and it will consume everything coming in to the serial port until it finds what it's looking for or until it times out.  That includes the :1 if you are using find to look for the :0 at the time.

Instead you either need to receive the whole string into memory and examine the string to see what it contains, or you need to manually process the data as it comes in character by character to decide what there is.


How to use existing (non-arduino-specific) library with subfolders in Arduino IDE? I have a generic c++ library that i'd like to use in an arduino project without making changes to the library code.
The library contains subfolders and files in the library include other files of the same library with includes of the form

#include "libraryroot/subfoldername/header.h"

I tried putting 'libaryroot' into C:/Users/Username/Documents/Arduino/libraries but while I can include headers that lie directly inside 'libraryroot' using #include <filename.h> (not #include <libraryroot/filename.h>), Arduino fails to find the headers these files include

How can I make use of such a library in Arduino without having to change the library?

To utilize subfolders with any name in an Arduino library, you must use the 1.5 library specification.

In libraries folder in your sketch folder, create a folder for the library. In this folder create a src subfolder and put the library source code into that subfolder. Then create a library.properties file in the root folder of the library with some dummy information. Fill the includes key with the main .h file of the library.

Documents/
  Arduino/
   libraries/
     FooLib/
      src/
       subfoldername/
        header.h
        some.h
        some.cpp
       foolib.h
       foolib.cpp
      library.properties

In code then use in #include the path with src folder as starting location.

#include <subfoldername/header.h>


portd not writing on digital ports 5 and 7 I try to build a function generator (preferably a sine) with an R-2R ladder and a Arduino Leonardo by Borderless Electronics.

For performance reasons one should use portd instead of digitalWrite.
However the signal is not at all what I want (just noise). So upon further investigation I found that the digital pins were never on HIGH. Pin 6 worked flawlessly. Furthermore I have tested the two failing pins with simple test programms and they behaved exactly as I would have expected.

Here is the code I use

 int sine[255];

 void setup()
 {
     pinMode(0, OUTPUT);
     pinMode(1, OUTPUT);
     pinMode(2, OUTPUT);
     pinMode(3, OUTPUT);
     pinMode(4, OUTPUT);
     pinMode(5, OUTPUT);
     pinMode(6, OUTPUT);
     pinMode(7, OUTPUT);

     float x;
     float y;
     for(int i=0;i<255;i++)
     {
          x=(float)i;
          y=sin((x/255)*2*PI);
          sine[i]=int(y*128)+128;
     }
}

void loop()
{
     for (int i=0;i<255;i++)
     {
          PORTD=sine[i];
          delayMicroseconds(10);
     }
}

I tested this with two Arduinos of the exactly same type.

Question: Why are pins 5 and 7 never on HIGH?

Edit: I have simplified everything down to one statement in the loop: portd = x;

I vary x manually

expected findings:

x  ->  #pin that is on high

0  -> None

1  -> 0

2  -> 1

4  -> 2

8  -> 3

...

128 -> 7

actual findings

x  ->  #pin that is on high

0  ->  None

1  ->  3

2  ->  2

4  ->  0

8  ->  1

16 ->  4

32 ->  None

64 ->  None

128->  6

I test this by simply connecting an oscilloscope to the output pins. The behaviour is extremely strange since the pins seem to be in random order, some even missing to portd. Furthermore portd = B11111111, according to the manual, is equivalent to portd = 255; and should set all pins on HIGH. But in my case it sets every pin to HIGH, except pins 5 and 7 are on LOW.

This is because on ATmega 32u4, which is used in Arduino Leonardo,  pins 5 and 7 are not mapped to port D but to port C and E respectively, as you can see in the ATmega 32u4 - Arduino Pin Mapping.

So you will have to:

either find another port where all 8 bits are available as digital outputs (note that I'm not sure one such port exists)
or split each sine[i] in 2 parts because you will have to work with 2 ports at the same time.


LCD 16x2 shows one line cut and the 7th column also cut My 16x2 LCD shows one line cut and the 7th column also cut:

Applying pressure:

My LCD module looks so similar to yours I decided risk to taking it apart for the purposes of taking pictures for to go along with the description.  It went back to together fine.
The black part I suggested pushing down on I'm going to call a "bezel", even though I'm not sure that's technically the correct term for it.
The pink color showing between the PCB and bezel is probably a "zebra strip" or elastomeric connector.  They conduct signals from LCD controller mounted on the PCB up to the LCD glass itself.  Sometimes they don't make good contact and so some segments of the LCD don't respond or respond poorly.  They may make better contact when you apply pressure to them.  If some or all of the segments start responding when you do that, it's a fairly good indication that this is a problem, though not an Arduino problem as such, it's a problem encountered with some frequency by Arduino users.
If you may need to replace the strips, or clean them, or adjust the bezel to apply more pressure to them.  Or just get another LCD module.
Back of one of my LCD modules that looks a lot like yours:

If you look at the back side of the board you may find that you can unclip the bezel; though it could also be soldered or glued etc.  If/when you do unclip it, the zebra strips and LCD glass will probably come free, perhaps with polarization filters as well.  You'll want to pay attention to the orientation of the everything so you know what you're doing when you put it back together.
I unclipped my the bezel on mine and the zebra strips (pink; they're not always pink) stayed with it. It is no so easy to see the "zebra" pattern on these particular strips.  Often they more alternating gray/white pattern.

Here's the PCB showing the contacts that the zebra strips mate to an the LED backlight spreader. Apologies for the dust.

The strip pattern is a little easier to see in this image.  You can also see the pattern of the conductors on the LCD glass.

You can try cleaning the strips and the glass and PCB where the make contact.  I would be careful what you clean with; look for trustworthy recommendations. In any case, keep your finger grease off of everything, either by using gloves or just washing and drying your hands before working on it.


Webservice C# JSON to Arduino I have a project in Microsoft Visual Studio C# and I have to pass JSON data to my Arduino via Ehternet Shield.

This is how it works:

Is it possible? How to do it?

Yes.

If you're using an Ethernet Shield, you should be able to run a webserver on the Arduino and simple do an HTTP request from your C# webservice to the Arduino.

Check this tutorial on how to write a webserver for arduino using the ethernet shield: http://arduino.cc/en/Tutorial/WebServer

Doing an HTTP request of any kind from C# should be easy enough and is not in the scope of this site.


Run two stepper at same time I am trying to run two stepper motor at same time with different RPM.
I decided to use two rotary encoder for change the RPM separately.

But,
I am in problem with driving stepper at same time due to the delay time of the step pulse.

How can I generate separate(different duty cycle) step pulses for stepper motors? It's the main problem that I faced.

I have used some Arduino libraries and all of that library has same system for step pulse generation. But, I couldn't understand those well.

void AH_EasyDriver::setSpeedRPM(long RPM)
{
   float DIV = RPM*this->MOTOR_RESOLUTION;
    this->STEP_DELAY =  60000000.0L/DIV;
 }

This function calculate the step time for given specific RPM

void AH_EasyDriver::move(int NUMBER_OF_STEPS)
{
   while(STEPS > 0) {
    if (micros() - this->LAST_STEP_TIME >= this->STEP_DELAY) {
      this->LAST_STEP_TIME = micros();
      STEPS--;
      stepMotor();
}
}

}

This function rotate the motor the motor in STEP_DELAY using stepMotor() function.

void AH_EasyDriver::stepMotor()
{
  digitalWrite(this->STEP_pin, HIGH);
  delayMicroseconds(100);
  digitalWrite(this->STEP_pin, LOW);
  delayMicroseconds(100);
}

This function makes CONSTANT step pulses.

I removed some lines in the function. This is the link for original .cpp file.
All of stepper controlling libraries has this functions.
I couldn't understand how this functions can change the RPM. Can someone explain this?

When using a normal stepper driver, you say the driver to do one step, by sending him one pulse. The length of these pulses does not have a meaning. they are constructed, so that the driver can sense them. The driver does not make smaller steps than 1 full step, if you don't tell him on extra pins (The library you use can utilize those pins too). So the stepMotor() function is correct. You can drive the motors with different speeds by doing a step for each motor in different intervals (different number of steps per time).

Your move() function blocks the execution of other code, until the motion is completed. You are doing this with the while( STEPS > 0 ) loop. You need to modify your code to be non-blocking. This is normally done in the way, that is shown by the BlinkWithoutDelay example of the Arduino IDE. You are using it too: You have to use the millis() or micros() function, to check if it is time to do a step.

Replace the while with an ´if´-statement:

if( STEPS > 0 )

and make the STEPS variable a member variable of the class instance. Then make sure you execute the function often enough, so that it will not miss the time to do a step. Do the same with the second motor. For example something that looks like this:

void setup(){
  ...
  stepper1.doSteps(100);
  stepper2.doSteps(200);
}

void loop(){
  stepper1.move();
  stepper2.move();
}

Here in the setup function the steppers are told to move 100 and 200 steps. (You would have to write the function doSteps(int number_of_steps) yourself). The motion is then done by the move() functions, when it is time to do so. Since these two functions are looped very fast, they shouldn't miss the time for a step.

This is also the way the AccelStepper library works, which is also a common stepper library.


Using AysncUDPMessage for ESP32 to send string data I am in search for some examples as to how can one use the AsyncUDPMessage in an Application for sending out UDP packets to a host with specific IP address and Port number from an ESP-WROOM-32 (Olimex ESP32-PoE) module?
The Class for AsyncUDPMessage in arduino-esp32 library inherits from Print.
I want to send sensor measurements to InfluxDB in the Line Protocol (InfluxDB specific).
Example
 imu,location=front,nodeid=node1 status=0.00,liac_x=-1.18,liac_y=0.02,liac_z=9.63,eul_x=0.00,eul_y=-6.81,eul_z=0.25 1538507409930

The above mentioned example is stored in the form of a String and the methods to send information via UDP viz. send() sendTo() all mention usage of AsyncUDPMessage as the first parameter.
goal
Send the above measurement to the particular Device's IP and port
udp.sendTo(Message, IPAddress(192,168,3,11), 8089);

I am currently using broadcastTo(const char * data, port) menthod to send information the InfluxDB instance.
Code
void loop(void) {

  DateTime now_time = rtc.now();

 // create a measurement
  influxMeasurement row("imu");
  row.addTag("location", "front");
  row.addTag("nodeid", "node1");

// get information from BNO055
  imu::Vector<3> li_ac = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);
  imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);
//  Serial.print(li_ac.x());
//  Serial.print(li_ac.y());
  row.addField("status", 0);
  row.addField("liac_x", li_ac.x());
  row.addField("liac_y", li_ac.y());
  row.addField("liac_z", li_ac.z());
  row.addField("eul_x", euler.x());
  row.addField("eul_y", euler.y());
  row.addField("eul_z", euler.z());

  // add timestamp
  row.addTimeStamp_ms(String(now_time.unixtime()) + String(millis()%1000));

  // print the Line Protocol output
  Serial.println(row.postString());

  // UDP Sending
  char buf[2048]; // make buffer for `broadcastTo()`
  row.postString().toCharArray(buf, sizeof(buf)); // string to char array
  // Serial.println(buf);
  udp.broadcastTo(buf ,8089);

  delay(100);
}

method
I create a Line protocol String, make a buffer, convert the string to char [] and send it out.
Question

how do I use AsyncUDPMessage so I can pass the string to it directly?

I am not sure but will char buf[2048] within a loop is a good idea as every time a buffer allocation might make the ESP32 run out of memory? And if AsyncUDPMessage can avoid this concern?

Use udp.print(row.postString().c_str())

AsyncUDPMessage in AsyncUDP library is only a buffer. It is used only in AsyncUDP send function:

size_t AsyncUDPPacket::send(AsyncUDPMessage &message)
{
    return write(message.data(), message.length());
}


Why is D3 not activating? So I made this circuit + a momentary push button on D2 and GND:

Because I don't use a real arduino, I use the RAW port to act like the +5V port. It all worked with a single LED without the npn transistor. Now, with the transistor, the strip of LED's doesn't turn off anymore when I hit the button. The code:

 #include <SoftwareSerial.h>

  #include <Keyboard.h>

  boolean toggle = false;
  int inPin = 2;
  int outPin = 3;

  int state = HIGH;
  int ledOn;
  int reading;
  int previous = LOW;

  long time = 0;
  long debounce = 200;

  void setup() {
    // make pin 2 an input and turn on the
    // pullup resistor so it goes high unless
    // connected to ground:
    pinMode(inPin, INPUT_PULLUP);
    pinMode(outPin, OUTPUT);
    Keyboard.begin();
  }

  void loop()
  {
    reading = digitalRead(inPin);
    ledOn = digitalRead(outPin);

    // if the input just went from LOW and HIGH and we've waited long enough
    // to ignore any noise on the circuit, toggle the output pin and remember
    // the time
    if ((reading == LOW) and (ledOn == LOW)) {
      state = HIGH;
      Keyboard.press((char) 128);
      Keyboard.press('r');
      delay(50);
      Keyboard.releaseAll();
      delay(200);
    }

    if ((reading == LOW) and (ledOn == HIGH)) {
      state = LOW;
      Keyboard.press((char) 32);
      delay(10);
      Keyboard.releaseAll();
      delay(100);
      Keyboard.press((char) 177);
      delay(10);
      Keyboard.releaseAll();
      delay(200);

      time = millis();
    }

    digitalWrite(outPin, state);

    previous = reading;
  }

You need to adjust the value of Rc, the collector current limiting resistor. When replacing the single LED with a strip of N LEDs of the same kind, you have increased N times the current required (that's why you need to use a BJT, because the Arduino I/O pins won't supply that much current). So, you need a new value for that resistor, let's call it Rc', much lower: Rc' = Rc/N. Otherwise, the old value may limit the current far below of what the LEDs need to light up.

But that's not all. You also need to add 2 resistors:

Rb: a current limiting resistor between D3 and the BJT base. Its value should be in the range 330 - 2200 Ohm. The higher the current draw of the LED strip, the lower the value of Rb should be.
Rpd: a pull-down resistor between the BJT base and ground to avoid it floating while D3 is not initialised as OUTPUT. Make it at least 20x the value of Rb.

All this should be enough to make it work.


What is commonly done to stop a servo after reaching desired position? When I started Arduino, I did not expect that everything must be contained in an infinite loop. I thought I could just write something like: motor start -> motor stop. But in actuality, what I get is motor start -> motor stop -> motor start -> ... forever and ever.

What is commonly done to stop a servo after it is in a desired position? Do I use servo.write(desired position) to keep it from turning? Do I detach the output wire?

What are some of the risks involved?

You do not "stop" a servo.

A servo is always running.  In a general sense, the servo is a control loop that takes as input a position target and applies force to hold at the requested target.  If you want the target to be maintained, then the servo must be running.

A servo motor contains electronics that are internally turning a DC motor on and off as necessary to hold the target position.  If the target does not match the current position, it turns on the motor to turn until the two match.  Once the output shaft reaches what you requested, the electronics inside the servo motor turn the motor "off".  Off meaning the DC motor is drawing little or no current.  The servo control loop is always running comparing the shaft position to a target.

If you powered off the entire servo motor, the position is not under control and could move.  For many applications if you unplugged the wires, the gears and motors apply enough friction that it would not turn.  But in general, you do not count on friction to make things work.

Do I use...Servo.Write(desired position) to keep it from turning?

Yes.  To tell a servo to stay at one position, you can just keep sending it the same target.

But you do not have to Write() again and again.  If you want, you can keep track of what the last setting was and apply only when you have a change.   For example, you can code like this:

if(position_target != position_last_set) {
  Servo.Write(position_target);
  position_last_set = position_target;
}

Regardless of your code, under the hood, Servo is constantly transmitting the position target to the servo motor.


Arduino-Pyserial communication on Python 3, Windows machine: Pyserial.write() doesn't seem to do anything I've recently gotten my hands on an Arduino (or rather a Genuino, but the overall architecture should be the same) UNO. I'm now using that Arduino to test how data is transmitted from a USB to Serial Connector to the Arduino.

I've already verified that data transmission from Arduino to the PC is possible, by using hTerm and PySerial. However, whenever I send data from Pyserial or hTerm, it doesn't show up in the Arduino serial terminal. Also, I'm using SoftwareSerial to set up a secondary serial terminal to see what the Arduino receives. (I'm using the standard serial port to send data to the terminal, and the SoftwareSerial Port to connect to the USB to Serial Connector.)

Here's my code so far:

Python side:

import serial
import time
import sys
import struct
ser = serial.Serial('COM3', 9600, timeout=0)
time.sleep(10)
while 1:
    print(ser.write(struct.pack('>B', 0)))
    time.sleep(2)
    print(1)
    sys.stdout.flush()

The Arduino side looks like this, and is essentially the default example:
https://www.arduino.cc/en/Tutorial/SoftwareSerialExample

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
  // put your setup code here, to run once:
  if (Serial) {
    Serial.end();
  }
  Serial.begin(9600);
  while (!Serial) {
    ;
  }

  Serial.println("Godnight moon!");

  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() {
  // put your main code here, to run repeatedly:
  mySerial.listen();
  if (mySerial.available() > 0) {
    Serial.println("Hello User");
    Serial.println(mySerial.read());
  }
}

The Terminal never prints "Hello User". Also, no other signals are being printed. By removing the if-condition, I get a whole lot of "Hello User" and "-1" in the Arduino IDE serial monitor.

Concerning my setup:

I've got an USB to Serial converter, which is connected as "COM3". On the other side, I have an Arduino UNO which is connected via USB to the same computer. The TX pin of the converter is connected to the RX pin of the Arduino and vice versa. Also, Ground is connected to Ground. Furthermore, I use Jupyter/IPython notebook to run my Python script, and the default Arduino IDE to compile programs for my Arduino. In the case there I received data from the Arduino, I used the script specified in the URL provided, which is very similar to the one I'm already showing here. Also, ser.write() is replaced by ser.read(1), so that it reads one byte at a time. My system is Windows 7 (64 Bit).

Edit: Here is an established connection between hTerm (a serial terminal) and the Python script while using com0com as a port emulator.

What do you think should come out?

I'm no expert with Python but you seem to be using struct pack, which I think prepends a number of bytes to the data to generate a 4 byte word.  You are using NULL, 0 to pack the structure.  When Serial.println() encounter a NULL it will assume that is the end of the string.  So you seem to be printing a zero byte string.

Oh and Serial.read() only reads one byte of data, so there is an issue with that too. I suspect that the write call has a similar issue, you normally need to supply a size parameter because its binary data.

Does that make sense?


How to access Attiny84 port B in Arduino IDE code? Referring to guide at High-low tech, I were able to flash ATTiny84 via UNO through Arduino IDE 1.6.7.

I loaded a simple blink LED program on IDE pin 0 (physical Attiny84 pin 13, PA0) and everything works fine for pin 0 till 7 at Port A.

But what if I want to access or blink a LED at one of the pins at Port B? Example, PB0 (physical pin 2)

The following is my current code to blink PA7

int led=7; //PA7

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

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

According to the ATtiny web-page the pin/ports are numbered as below:

The physical pin 2 is the Arduino ATtiny core pin 10. You can also find this well documented in the pins_arduino.h file.

Cheers!


Nick Gammon's Hex Converter Error I'm trying to add a bootloader hex to Nick Gammon's Atmega Board Programmer sketch, and I can't seem to get a hex file to convert.

I need to convert "Arduino-usbserial-atmega16u2-Uno-Rev3.hex", but that wasn't working so I thought I'd try converting one that's already used in the sketch, "Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex", but that's not working either. I've followed the instructions from http://www.gammon.com.au/bootloader

I've tried it using Wine and Paralells. Clicking the copy button when using Wine causes the program to stop responding.

Here is a screenshot of the error:

Thank you


Ways to add pins in an arduino I'm making a project for school where I'm using flex sensors and converting that into words on an LCD (similar to the signing glove if you're familiar with that).
I ran into a problem since the Arduino I'm using doesn't have enough pins for all of my flex sensors and my LCD monitor.

I'm considering getting another Arduino with more pins but I might not have time to order it since my project is due in a couple of days. I was thinking about connecting two arduinos but I'm not sure if that would work (first year coding/engineering student) Any other suggestions as to how I can create more pins?

Your input is greatly appreciated!

The Arduino I'm using is a sparkfun redboard (it only has 6 analog pins and a separate place to plug in the LCD monitor which I connected to where it says ISP f you look on the link you will see what I'm talking about SparkFun RedBoard - Programmed with Arduino).

I'm using four flex sensors

LCD:

This can be done with the existing board. LCD can be driven by only with the digital pins. Check the below link for the wiring diagram.

https://www.arduino.cc/en/Tutorial/LiquidCrystalDisplay

Since there are 6 Analog pins available, all flex sensors can be easily connected.


Control the "TV remote" My idea is to use Arduino to control the TV remote. Not make the Arduino become a TV remote, I want to make an Arduino that can touch button of a remote control.

Any ideas?

My rather fancy solution would be to make a 3 axis device with x and y controlled by stepper motors and z a simple solenoid to press the buttons.
For extra marks you could add a camera and try to recognise the buttons in software so any remote would work.
How do you plan to control the arduino?  Perhaps with a remote controller?


HC-05/Arduino receiving spam data I connected everything properly. On the first try I did receive data as  I was supposed to. I then wrote some logic, re-uploaded and started receiving crazy spam.

My serial monitor is getting spammed with:

question marks if the variable is char, or;
25252525252 if the variable is int, or;
-1 if variable is String.

I'm monitoring at 38400 baud which is the same as my Serial.begin().

Any ideas ?

Code:

#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

#define MIN_PULSE_WIDTH 650
#define MAX_PULSE_WIDTH 2350
#define DEFAULT_PULSE_WIDTH 1500
#define FREQUENCY 50

char data = 'a';

void setup()
{
  analogReference(DEFAULT);

  Serial.begin(38400);

  pwm.begin();
  pwm.setPWMFreq(FREQUENCY);
  Serial.println("hello world");
}

void loop()
{
  data = Serial.read();
  Serial.println(data);
  Serial.flush();
  if (data == 'a'){
    pwm.setPWM(0, 0, pulseWidth(90));
  }
  if (data == 's'){
    pwm.setPWM(0, 0, pulseWidth(30));
  }
  delay(1000);
  //printing time in seconds
}

int pulseWidth(int angle)
{
  int pulse_wide, analog_value;
  pulse_wide = map(angle, 0, 180, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);
  analog_value = int(float(pulse_wide) / 1000000 * FREQUENCY * 4096);

  return analog_value;
}

Serial.read() returns -1 if no data is available. It doesn't wait for the byte. Test for -1 or use Serial.available() as any example does.

Replace Serial.print(data) with Serial.write(data) to get the data echoed back unchanged.


Problems when attaching a second ultrasound sensor (HC SR04) I am working on an obstacle avoiding robot. It uses an ultrasound sensor to avoid obstacles, but currently has trouble avoiding objects that are diagonal to it. Thus, i want to add a second ultrasound sensor, and alternate their readings. I am testing the code, which should look right and then leftn and return the distances. The code worked for just one ultrasound.  and it is a follows:

#include <NewPing.h>
#include <Servo.h>

#define trig_pin1 A1 //analog input 1
#define echo_pin1 A2 //analog input 2
#define trig_pin2 A3 //analog input 1
#define echo_pin2 A4 //analog input 2
int distance1 = 100;
int distance2 = 100;

#define maximum_distance 200 //sensor function
Servo servo1; //our servo name
Servo servo2;
NewPing sonar1(trig_pin1, echo_pin1, maximum_distance);
NewPing sonar2(trig_pin2, echo_pin2, maximum_distance);
void setup() {
  // put your setup code here, to run once:
  servo1.attach(11); //our servo pin
  servo1.write(90);
  servo2.attach(6); //our servo pin
  servo2.write(90);

  distance1 = readPing1();
  distance2 = readPing2();
  delay(100);
  distance1 = readPing1();
  distance2 = readPing2();
  delay(100);
  distance1 = readPing1();
  distance2 = readPing2();
  delay(100);
  distance1 = readPing1();
  distance2 = readPing2();
  delay(100);
}

void loop() {
    int distanceRight = 0;
  int distanceLeft = 0;

        distanceRight = lookRight();
    delay(300);
    distanceLeft = lookLeft();
    delay(300);
  }
}

int readPing1(){
  delay(10);
  int cm = sonar1.ping_cm();
  if (cm==0){
    cm=250;
  }
  return cm;
}

int lookRight(){
  servo1.write(50);
  delay(500);
  int distance1 = readPing1();
  delay(100);
  servo1.write(115);
  return distance1;
}

int readPing2(){
  delay(10);
  int cm = sonar2.ping_cm();
  if (cm==0){
    cm=250;
  }
  return cm;
  }
int lookLeft(){
  servo2.write(170);
  delay(500);
  int distance2 = readPing2();
  delay(100);
  servo2.write(115);
  return distance2;
  delay(100);
}

I get the following error:
'readPing1' was not declared in this scope

and I get the same error for the readPing2 function. Why could this be?

It turns out I had an extra "}" after the void loop function. The code worked as expected after removing it


Not able to add JSON data to Arduino data In my recent project, I'm working with Arduino with JSON.

I made software on JSON. Now, I want to send data from this software to my Arduino. Serial communication is done between Arduino and JSON. But somehow, I can't able to get proper data from JSON to my Arduino. So, I google out and find library named ArduinoJson. And here, I found out example code. So, I tried out that code and modified based on my requirement.

Here, below is my code.

Now, Software sends me value. And I split it out into three variable MAP_Json, TPS_Json, and LOAD_Json.
In Arduino side, I have already the value of MAP, TPS, and LOAD.

So, now my main intention is to compare MAP_Json with MAP & TPS_Json with TPS. If they are matched then LOAD_Json is added to LOAD. But, when I try it out, then LOAD_Json not added to LOAD. I don't understand why this happened?

 #include <ArduinoJson.h>

//----------------------------For MAP calculation----------------------------//
float MAP_MIN = 0.85;
float MAP_MAX = 1.90;

int LOAD_MIN_MAP[] = {1, 2};
int LOAD_MAX_MAP[] = {3, 4};

float mMAP[2] = {};
float yMAP[2] = {};

int i, j, a;
float MAP, mFinalMAP, yFinalMAP;

//----------------------------For TPS calculation----------------------------//
float TPS_MIN = 0.00;
float TPS_MAX = 5.00;

int LOAD_MIN_TPS[] = {1, 3};
int LOAD_MAX_TPS[] = {2, 4};

float mTPS[2] = {};
float yTPS[2] = {};

int k, l, b;
float TPS, mFinalTPS, yFinalTPS;

//----------------------------For LOAD calculation---------------------------//
int LOAD_MIN = 2;
int LOAD_MAX = 100;

float injTime_MIN_LOAD[] = {8.00, 9.06};
float injTime_MAX_LOAD[] = {10.60, 11.86};

float mLOAD[2] = {};
float yLOAD[2] = {};

int m, n, c;
float LOAD, mFinalLOAD, yFinalLOAD;

//------------------------------ Variable ---------------------------------//

float load;

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

void loop()
{
  //----------------------ARDUINO DATA-------------------------//

  //----------------------------MAP----------------------------//

  MAP = analogRead(A0) * (5.0 / 1023.0);

  for(a = 0; a < 2; a++)
  {
    mMAP[i] = (LOAD_MIN_MAP[a] - LOAD_MIN_MAP[a]) / (MAP_MAX - MAP_MIN);
    yMAP[j] = mMAP[i] * (MAP - MAP_MIN) + LOAD_MIN_MAP[a];
  }

  //----------------------------TPS----------------------------//

  TPS = analogRead(A1) * (5.0 / 1023.0);

  for(b = 0; b < 2; b++)
  {
    mTPS[k] = (LOAD_MAX_TPS[b] - LOAD_MIN_TPS[b]) / (TPS_MAX - TPS_MIN);
    yTPS[l] = mTPS[k] * (TPS - TPS_MIN) + LOAD_MIN_TPS[b];
  }

  //----------------TPS/MAP CALLIBRATION / LOAD----------------//

  mFinalTPS = (yMAP[1] - yMAP[0]) / (TPS_MAX - TPS_MIN);
  yFinalTPS = mFinalTPS * (TPS - TPS_MIN) + yMAP[0];

  mFinalMAP = (yTPS[1] - yTPS[0]) / (MAP_MAX - MAP_MIN);
  yFinalMAP = mFinalMAP * (MAP - MAP_MIN) + yTPS[0];

  LOAD = (yFinalTPS + yFinalMAP) / 2;

  Serial.print("T : ");
  Serial.print(TPS);
  Serial.print("\t");
  Serial.print("M : ");
  Serial.print(MAP);
  Serial.print("\t");
  Serial.print("L : ");
  Serial.print(LOAD);
  Serial.print("\t");

  while(!Serial)
  {
    // wait serial port initialization
  }

  StaticJsonBuffer<200> jsonBuffer;

  char json[] = "{\"TPS\":1.67, \"MAP\":1.83,\"LOAD\":30}"; // JSON DATA

  JsonObject& root = jsonBuffer.parseObject(json);

  // Test if parsing succeeds.
  if(!root.success())
  {
    Serial.println("parseObject() failed");
    return;
  }

  // Splitted JSON DATA

  float TPS_Json = root["TPS"];
  float MAP_Json = root["MAP"];
  float LOAD_Json = root["LOAD"];

  Serial.print("T_J : ");
  Serial.print(TPS_Json);
  Serial.print("\t");
  Serial.print("M_J : ");
  Serial.print(MAP_Json);
  Serial.print("\t");
  Serial.print("L_J : ");
  Serial.print(LOAD_Json);
  Serial.print("\t");

  //Compare JSON DATA and ARDUINO DATA

  if(TPS_Json == TPS && MAP_Json == MAP) //If matched
  {
    load = LOAD_Json + LOAD;            // Add LOAD_Json and LOAD
  }

  Serial.print("Final Load :");
  Serial.print(load);
  Serial.print("\n");
}

EDIT 1: Improve question formatting

EDIT 2: Upload Complete code

Comparison of floating point values is nigh on impossible. They aren't as accurate as you may think anyway, and two values have to be precisely the same to be considered equal - not something that is easy to achieve (23.4893782 != 23.4892480).

Instead you should either round them to a specific precision, or take the difference between the two values and decide if they are "close enough".

E.g.:

float diff = abs(TPS - TPS_Json);
if (diff < 0.5) {
    // do something
}


Software Serial and multiple shields for Arduino Uno I have a SIM900 GPRS/GSM Shield (details here) and I am looking to stack a GPS shield (such as this one here).

My question is: I believe that they both require software serial, also it says to use software serial on D7 and D8 for both. Is this possible on an Uno?

I am a bit confused at if software serial has to have these two specific pins, or if these are just what is chosen on schematics?

What would be the most effective way to stack these two shields so they don't interfere with each other?

EDIT: Using a gps shield such as this gives the option  of

  If you need to move the software serial port pins, they can be custom-routed to any other pin by cutting the solder jumpers between pins GPS-RX and D8 and/or GPS-TX and D9.

This isn't entirely clear to me, but am I right in thinking it means I can have multiple software serials on my Uno, just using different pins?

SoftwareSerial can use any pins. That's the whole point of it. However, some shields are wired to use specific pins. If two shields try and use the same pins then you can't use them together. Not stacked, anyway. You will have to use flying leads, or physically alter the shield (cutting tracks, soldering in "bodge" wires) to use them together.

That said, though, you can only use ONE SoftwareSerial port reliably at a time. That means, regardless of what pins they use, you can't use two shields together that require pins other than 0 and 1 (hardware serial).

To use them both you will need a board with multiple hardware UART ports and modify the shields (as mentioned above) to use the correct pins for those UART ports.


Reconstruct uint32_t from char array to RTC.set I am currently experimenting with a Digistump ATTiny85. Since it has no Serial, I use the basic DigiUSB library for communication. The RTC library used is this one: https://github.com/JChristensen/DS3232RTC/. The DigiUSB library is from Digispark.

I attached a DS3232 via TWI to the Digistump, because I want to use this construct as a USB-Realtime-Clock.

Initially setting the time in the setup method works as follows

  RTC.set(1532341020);

But I am unable to transfer the time via the pseudo serial connection and set it remotely. What I've tried so far:

Using union with char and uint32_t. Althougt the char representation is correct (tried DigiUSB.println()), the uint32_t representation of this union is not what I need.
Tried to adapt to some shifting examples, but seriously got lost here. All examples where about 4 byte streams.
atoi and some other functions with no success.

Here is my current sketch

#include <DS3232RTC.h>
#include <DigiUSB.h>

//union ArrayToInteger {
//  char array[10];
//  uint32_t integer;
//};

unsigned char foo[10];
uint32_t num;

void setup() {
  RTC.begin();
  //RTC.set(1532341020);
  DigiUSB.begin();
}

void loop() {
  if (DigiUSB.available() >= 10) {
    for (int i=0; i<=10; i++) {
    foo[i] = DigiUSB.read();
  }
  RTC.set((uint32_t)foo);
  DigiUSB.delay(100);
  DigiUSB.refresh();
  //DigiUSB.println(_foo.array);
  DigiUSB.println(RTC.get());
} else {
  DigiUSB.refresh();
  DigiUSB.println(RTC.get());
  DigiUSB.refresh();
  DigiUSB.delay(1000);
  }
}

In the end I need the a char _foo 0123456789 represented as/converted to uint32_t num 0123456789

Kinda stuck here. Can anyone point me in the right direction ore provide an example?

There are several possible issues here:

can you send the number, as a string, from the PC to the ATtiny?
can you convert the string to an actual number?
can you give this number to the RTC?

The phrasing of your question sounds like your issue is with the
conversion. However that is easily handled with atol(). Here is a test
program I tried on my Uno:

void setup() {
    char time_string[] = "1532341020";
    uint32_t time_number = atol(time_string);

    Serial.begin(9600);
    Serial.print("string: \"");
    Serial.print(time_string);
    Serial.print("\", number = ");
    Serial.println(time_number);
}

The output is:

string: "1532341020", number = 1532341020


Nth-Light LED Strip power connections Based on this question on the Adafruit forum for Nth-Light Narrow LED Flexible Strip Light (https://www.adafruit.com/product/3683) and the image below is it safe to connect from the 12v source + a wire to the Vin (orange wire) or it is better to connect to another DC barrel?

If your 12V power supply has enough current to drive your LED strip at its maximum power, plus the Arduino's power supply, plus about 10-20% of "wiggle room" you should be fine. As the LED strip draws spikes of current the voltage from your power supply might bounce around a little, but the Arduino's voltage regulator would be fine with as little as 7.5V input.

Note that your Arduino's voltage regulator will get hot if you use much current from the Ardunio's 5V rails, since it has to regulate 12V down to 5V and the linear regulator on the Arduino converts the extra voltage to heat.