Slice byte-stream into bit pieces I receive byte data from a RS-232 device with Serial.read();. Now I need to slice this down in bit-pieces:

value1: 15bits
value2: 7bits
value3: 9bits
value4: 12bits
and so on

Data from the stream (switch them around for better understanding):

Byte 1: 00101100 => 00110100 (least significant byte first)
Byte 2: 10011011 => 11011001
Byte 3: 00110011 => 11001100
Byte 4: 11101000 => 00010111
Byte 5: 01001100 => 00110010
Byte 6: 01100111 => 11100110

Now the least significant is first.

value1: 00110100.1101100[1] => 6956
Need to cut of the last bit of the second byte
value2: 1.110011[00] => 103
Add the last bit of the second byte and cut off the last two bits of the third byte
value3: 00.0001011[1] => 416
Add the last two bits of the third byte and cut off the last bit of the fourth byte
value4: 1.00110010.111[00110] => 3737
Add the last bit of the fourth byte and cut off the last 5 bits of the fifth byte

Now the question: How do I realize this from programming side. I'm lost.

Note: This is an answer that OP originally edited into his question.

I gather the data into an array of bytes data[125].

Then I gather the relevant bytes per value and stack them together:

long var = (data[4]<<8) + (data[3]);

I shift them so the relevant bytes start first

var=var>>3;

Afterwards I mask them with the RIGHT mask

var=var & 0xFF;

For the example in my question:

long var = (data[1]<<8) + (data[0]); // I need two bytes
var=var>>1; // shift them to the right one bit
var=var & 0x7FFF; // mask it with "0111 1111 1111 1111"


How do I use digital pin on sensor to analog on arduino uno I am working on a autonomous fire extinguisher.i have run out of pins.I have the following question in my mind while working on my project

Is it necessary that the DO pin in a flame sensor must be in a PWM digital pin in Arduino.i have this doubt since when I connected it to non PWM pin it didn't worked.

Secondly it is possible for me to use the analog pin in Arduino for the DO pin of the flame sensor or trigger/echo pins of the ultrasonic sensor.

Thanks.

PWM stands for Puls Width Modulation and is only available when the Digital Pin is in OUTPUT mode.

And YES, you can connect the flame sensor's D0 to any digital pin on the Arduino.

And yes it is possible to connect the flame sensor's D0 to a analog pin, but why not use the A0 from the flame sensor and connect it toi a analog pin on the Arduino?


Trying to flash ATTiny85 bootloader using FT232R in the Arduino IDE I have a FT232R that I want to use to flash my ATTiny85 bootloader in the Arduino IDE, can someone help me out on this? I don't want to get a AVR programmer.

A bootloader is a program that gets loaded into the bare microcontroller to handle a number of low level tasks. One of those tasks is the ability to load a program over UART (serial).

As such, the bootloader can be loaded into the microcontroller using a AVR programmer. Once this has occurred, you can then easily load in programs with the FT232R.

It is possible to use the bitbang mode on the FT232R to load the bootloader into an Arduino board, hence replacing the AVR programmer. So, it can work but it isn't easy.

As suggested by per1234, there is some instructions on how to do this to an Arduino Diecimila on the Adafruit website: Programming the Arduino Bootloader
In general the full page has a lot of useful information: Full page


Why is 1020 steps used for crossfading colors on an RGB LED? I'm looking into how to smoothly crossfade between colors on an RGB LED with the Arduino and I've found this piece of code for doing it:
https://www.arduino.cc/en/Tutorial/ColorCrossfader

I understand all parts of the code except for one thing.
The values for red, green and blue are changed incrementally through 1020 steps, because 255*4 = 1020.
But WHY 4? There are 3 colors, and 255 * 3 = 765. So why not 765 steps?

Extract from code:

int wait = 10;      // 10ms internal crossFade delay; increase for slower fades

for (int i = 0; i <= 1020; i++) {
  redVal = calculateVal(stepR, redVal, i);
  grnVal = calculateVal(stepG, grnVal, i);
  bluVal = calculateVal(stepB, bluVal, i);

  analogWrite(redPin, redVal);   // Write current values to LED pins
  analogWrite(grnPin, grnVal);
  analogWrite(bluPin, bluVal);

  delay(wait); // Pause for 'wait' milliseconds before resuming the loop

  if (DEBUG) { // If we want serial output, print it at the
    if (i == 0 or i % loopCount == 0) { // beginning, and every loopCount times
    }
    DEBUG += 1;
  }
}

The 1020 in the loop determines the time taken to make the crossfade from the current colour to the next - not the total cycle as you seem to think. In the main loop we have

crossFade(red);
crossFade(green);
crossFade(blue);
crossFade(yellow);

And each of these crossfades will take 1024 * wait ms to complete. 'wait' is set to 10 ms so I would expect it to take 10.24 s to complete a fade from one colour to the next.

[Edit]

I think the large number (1020) is just to give a fine resolution in the steps calculation which is all done with integers. (What struck me as odd is that it doesn't use 256 * 4 = 1024.) The larger we make this number the finer the step resolution becomes. With coarse steps the ramp will complete too early.

Let's say we had 255 steps and we wish to go from 134 to 0.

step = 255 / (endValue - prevValue)
step = 255 / (134 - 0 ) = 1.9 which will be rounded down to 1.

This means that the crossfade will be complete in 134 steps instead of 255. i.e., it will finish 47% early.

If we use 1020 steps and we wish to go from 134 to 0.

step = 1020 / (endValue - prevValue)
step = 1020 / (134 - 0 ) = 7.6 which will be rounded down to 7.

This means that the crossfade will be complete in 938 steps instead of 1020. i.e., it will finish 8% early.


Which Microcontroller to use I want to use a wifi shield, as well as a 2.8 inch touch LCD shield; both would fit the arduino uno V3 nicely.  Is that the best microcontroller to use

To answer your first question, regarding stacking a WiFi Arduino Shield on top of a LCD Shield:

  can I stack them simultaneously

The obvious answer is - it depends on the shields. Each shield might use a different set of Arduino I/O pins, making them unavailable to the next shield stacked on top of it.

for example, this formal Arduino WiFi shield makes I/O pins 10, 11, 12, 13 and 7 (on Arduino Uno) unavailable to the next top shield.

Unfortunately, this LCD KeyPad shield needs pins 7 and 10 available (among others) in order to function properly. This makes it incompatible for stacking on top of the WiFi shield mentioned above (or vice versa).

It doesn't mean that there is no way that any LCD shield could be stacked on top of a WiFi shield, but to be honest, I couldn't easily find any LCD shield that won't collide with a WiFI shield pins. You might want to change approach and send the WiFi data using the built-in Serial to a computer.

  Is that the best microcontroller to use

If there would have been a manifest to this website, I'm sure that "The best product is the one that meet your needs best" would be it's first sentence. In order for someone with experience to answer what is best, (s)he would need to know your exact needs. Since you are still not sure what they are, and just want to play around a bit, I imagine that the classic Arduino Uno R3 could help you find your way, especially if you are doing your first steps with Arduino.


Loops fail after ~5 minutes when making two API calls every 10 seconds using WiFi client I am running into an issue with a loop call on an Arduino MKR1000. I have tried the solutions suggested in this question and it usually works for 5 minutes and then collapses.  I am trying to make two calls to different APIs every 10 seconds and update something on the Arduino accordingly, but the loops seem to be getting out of sync after a few minutes. Here is the code - I tried to shorten it...

#include <Time.h>
#include <SPI.h>
#include <WiFi101.h>
#include "arduino_secrets.h"

// put your local wifi info here
const char* ssid     = SECRET_SSID;
const char* password = SECRET_PASS;

const char* host = "bustime.mta.info";

void setup() {
  Serial.begin(9600);
  delay(10);
 // connecting to a WiFi network
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(300);
    Serial.print(". ");
  }
}

void loop() {
  Serial.println("START THE LOOP");
  // Use WiFiclient class to create TCP connections
  WiFiClient client;
  WiFiClient client2;
  char * serviceDeliveryString = new char[40]();
  strcpy(serviceDeliveryString, "/ServiceDelivery");
  char * responseTimestampString = new char[40]();
  strcpy(responseTimestampString, "<ResponseTimestamp>");
  char * TString = new char[40]();
  strcpy(TString, "T");

  if (!client.connect(host, 80)) {
    lcd.clear();
    lcd.gotoXY(0, 0);
    lcd.string(connectionFailed);
    delay(2000);
    return;
  }

  //connect to schedule data
  if (!client2.connect(host, 80)) {
    lcd.clear();
    lcd.gotoXY(0, 0);
    lcd.string(connectionFailed);
    delay(2000);
    return;
  }

  char * req1full = new char [100]();
  strcat(req1full, "GET /api/siri/stop-monitoring.xml?key=KEY&OperatorRef=MTA");
  strcat(req1full, " HTTP/1.1");
  client.println(req1full);
  client.println("Host: bustime.mta.info");
  client.println("Connection: close\r\n");

  char * req2full = new char [100]();
  strcat(req2full, "GET /api/where/schedule-for-stop/MTA_");
  strcat(req2full, stopNum);
  strcat(req2full, ".xml?");
  strcat(req2full, "key=KEY HTTP/1.1");
  Serial.println(req2full);
  client2.println(req2full);
  client2.println("Host: bustime.mta.info");
  client2.println("Connection: close\r\n");

  //Pause long enough for the connection to happen. Make this longer if you have issues.
  delay(1000);

  while(client.available()){
    if (client.findUntil(responseTimestampString, serviceDeliveryString)){
      Serial.println("inside client...");
      client.findUntil(TString, serviceDeliveryString);
      String mtaTime = client.readStringUntil('.');
      Serial.println(mtaTime);
    }
    delay(10);
  }

  while(client2.available()){
    if (client2.findUntil("<currentTime>", "/data")){
      Serial.println("inside client2...");
      String mtaTime2 = client2.readStringUntil('<');
      Serial.println(mtaTime2);
    }
    delay(10);
  }

  client.stop();
  client2.stop();
  delay(9000);

}

The output starts out looking good:

START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
inside client...
22:13:38
inside client...
22:13:38
inside client2...
1541211218146
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
inside client...
22:13:51
inside client...
22:13:51
inside client2...
1541211231815
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
inside client...
22:14:04
inside client...
22:14:04
inside client2...
1541211244465

But eventually something seems to happen with the loops and this is the final output, when it should keep running:

inside client...
22:19:02
inside client...
22:19:02
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
START THE LOOP

Any suggestions for how to fix this?

You keep calling new to allocate memory but you never free it.  This is a memory leak and eventually you run out.  Instead of constantly creating new arrays, why don't you make those global or static.  Or even just local arrays if you don't need them to be persistent.  On a microcontroller you really don't want to be using new unless absolutely necessary.


ESP32 softAP SSID not const I would like to be able to set the wifi SSID in the setup(), so I can customize it based on the MAC address or something similar. (avoiding to ESP's with the same code having the same SSID). However since it requires a const it does not seem to be possible, or am I missing something?
I'm using platformIO if that matters...

A const parameter to a function doesn't define what can be passed. It is, instead, a "promise" by the function that it will not modify the data you pass it.
In C when you pass a "string" (which is actually an array of characters) to a function you don't actually pass the string (as in the content). You really just pass a pointer to the location in memory where the string is stored.
It is perfectly possible for a function to then make modifications to that passed "string", which will be modifying the original data in memory. That is not really desirable in many situations.
So by flagging the parameter as const you tell the compiler "From this moment onwards the data pointed to by this variable must not be changed". All attempts to write to the memory using that variable will be blocked by the compiler.
There's no actual difference between, say, a char * and a const char * other than how the compiler treats attempts to write to them.
When you pass a char * to a function that is expecting a const char * the pointer is "upgraded" to a constant so that no attempts to change the data will be allowed.
The converse is not allowed though - you can't (or shouldn't) try and convert a const char * to a char * as on some systems ("Princeton" architecture systems with a single monolithic memory address space) the pointer could be pointing to data stored in flash, and an attempt to write to that will obviously fail.
The function you are calling to set the SSID is merely promising that it won't attempt to change the data you pass it. It doesn't matter if it's a constant or not - both will be treated as a constant and not be changed.


BMP 280 exact Altimeter readings I was just going through this pressure sensor tutorial.

What I want to know is how can I set the exact altimeter in my readings depending upon my different geographical place ? or may be if I am attaching the sensor to my balloon.

The tutorial sample source code has the line:

Serial.print(bmp.readAltitude(1013.25)); // this should be adjusted to your local forcase

That 1013.25 value should be the local pressure at sea level in hundreds of Pa. If want to show altitude above ground level, you will need to know that for your location and write your code to calculate the altitude offset.

The sensor can't know location -- it only measures pressure. The AdaFruit library provides the altitude conversion, but being generic, it relies on several assumptions.


waiting for a set number of inputs in an array to be reached How do i have code wait for an x number of inputs be reached in an array before doing anything else?

int largestindex = 0;
int learnindex=0;

    void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
    learn[learnindex]=pitch;
     learnindex++;
    }

    while(learn[largestindex]==0){
          MIDI.read();
          if (learn[largestindex]!=0){
           break;
              }

If the call to MIDI.read() is a blocking call (it stays in there until it has a value) then you are pretty close:

const int NumberOfInputs (42);
for (int index = 0; index < NumberOfInputs; ++index)
{
    MIDI.read();
}

You can simplify you handler by post incrementing the learnindex counter as you use it.  (Post increment will happen after the value has been 'used')

void MyHandleNoteOn(byte channel, byte pitch, byte velocity)
{
    learn[learnindex++] = pitch;
}

When you increment a variable on its own line its usually better to pre increment it, because you aren't using the value and it might result in quicker execution.  However remember you are increasing the value before using it, so if you use it as above you end up accessing the array element one higher than you intended to!

int learnIndex = 0;
++learnindex;            // Pre-increment it to 1
learn[learnIndex++] = 1; // Set element 1 to 1.
learn[++learnIndex] = 3; // Set element 3 to 3.


Problem burning bootloader on ATmega328P using internal clock I'm trying to burn the arduino bootloader onto my ATmega328P so it uses the internal clock. I followed the tutorial in this page but I'm getting this error.

avrdude: Version 6.3, compiled on Dec 16 2016 at 13:33:19
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

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

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

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

avrdude: AVR device initialized and ready to accept instructions

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

avrdude: Device signature = 0x000000 (retrying)

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

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.02s

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

avrdude done.  Thank you.

I tried placing a cap from reset to ground but it doesn't wort either.
Any idea on what might be wrong with my procedure?

Thanks

[EDIT]

I followed the procedure described at the bottom of the page linked (Minimal Circuit (Eliminating the External Clock)).
I used the bootloader in "breadboard-1-6-x.zip"
I am using the Arduino IDE v1.8.1

If your ATMEGA328P has already been used with a crystal or already has a bootloader on it, then the fuses will be set to expect a crystal oscillator. In this case, you must initially have a crystal & the associated 2 capacitors connected. Once you have succeeded in burning the bootloader (this process also sets the fuses) you can dispense with the crystal.


How to get 3v3 pins on Arduino Mega Sensor shield v2.0? I am using Arduino mega and a sensor shield (picture attached below). I need to connect three different wires to 3.3 V input. Can anybody suggest how can I achieve the same? What voltage do the VCC pins of all digital and analog pins on the sensor shield have?

They are all 5V as the Mega2560 uses 5 V logic.  However, there is a 3V3 pin at the bottom, second pin from the left, that you could use:

However, unfortunately, the pin isn't protruding above the shield, so you'll have to make an ugly solder link to the top of the pin. Either that, or remove the row of pins and replace with a female header (carefully avoiding the SD card pins):

As an aside, the Iteaduino MEGA 2560 works at 3V3 but unfortunately the Mega shield that you have won't fit it.

The Uno equivalent of your shield will fit it though:


Obstacle avoidance algorithm TARGET

The task I have taken as a challenge is to make a GPS-guided robot incorporated with features like Arduino for programming, ultrasonic sensors for obstacle avoidance and a GPS module to specify the way points location (from starting point to end point).

This robot should be able to avoid both static and moving obstacles while moving to its end point assigned from the GPS. I have found the robot  manoeuvring around both static and moving obstacles to be a bit challenging. I was wondering if there is an effective obstacle avoidance algorithm that I can use.

I will appreciate it if I could get some helpful suggestions and insights.

In a real world scenario, your robot would know its start point and end point but due the limited range of its sensors (radar/ sonar/ visual) and the inability to "see" around corners, it would never be able to plan a full route at the very start of its journey. It would need to start the journey, detect obstacles as it moved and then re-calculate its path as it proceeds to its destination.

There is a very simple weighted index algorithm called the 'Bubble Rebound Algorithm' to accomplish this type of maneouvering developed by IOAN SUSNEA, VIOREL MINZU and GRIGORE VASILIU.

Be aware however, that this is NOT a 'Maze Solving' algorithm. It is only meant for avoiding obstacles.

But first I suggest you take a look at my blog post about the python simulation I wrote using this algorithm. This will help you understand what is going on and give you a broad idea about how the problem is solved.

I also made two very important modifications (which I have described in the blog) to the algorithm that help the robot actually reach a destination.

On the blog post you will find a link to the source code hosted at codeskulptor and a YouTube video demonstrating the algorithm at work.


Calculate OCR2A from audio frequency I'm working on a Arduino-based synthesizer using this tutorial, specifically using a wavetable and 1-bit DAC. I understand that the value for OCR2A register sets the frequency, but how do I calculate the value?

I've seen this list of notes which is great, but I want arbitrary frequencies in Hz...

Here's the code I'm working from:

#include <avr/interrupt.h>

// sinewave parameters
#define FREQ 18
#define PI2 6.283185    // 2*PI saves calculation later
#define AMP 127         // scaling factor for sine wave
#define OFFSET 128      // offset shifts wave to all >0 values

#define LENGTH 256      // length of the wave lookup table
byte wave[LENGTH];      // wavetable

void setup() {

  // populate wavetable
  for (int i = 0; i < LENGTH; i++) {
    float v = (AMP * sin((PI2 / LENGTH) * i));
    wave[i] = int(v + OFFSET);
  }

  // set timer1 for 8-bit fast PWM output
  pinMode(9, OUTPUT);       // make timer’s PWM pin an output
  TCCR1B = (1 << CS10);     // set prescaler to full 16MHz
  TCCR1A |= (1 << COM1A1);  // pin low when TCNT1=OCR1A
  TCCR1A |= (1 << WGM10);   // use 8-bit fast PWM mode
  TCCR1B |= (1 << WGM12);

  // set up timer2 to call ISR
  TCCR2A = 0;             // no options in control register A
  TCCR2B = (1 << CS21);   // set prescaler to divide by 8
  TIMSK2 = (1 << OCIE2A); // call ISR when TCNT2 = OCRA2
  OCR2A = FREQ;           // set frequency of generated wave
  sei();                  // enable interrupts to generate waveform!
}

void loop() {
  // nothing to do here!
}

// called every time TCNT2 = OCR2A
ISR (TIMER2_COMPA_vect) {   // called when TCNT2 == OCR2A
  static byte index = 0;    // points to each table entry
  OCR1AL = wave[index++];   // update the PWM output
  asm("NOP; NOP");          // fine tuning
  TCNT2 = 6;                // timing to compensate for ISR run time
}

The equation to calculate it is given in the first article you linked:

The 2MHz value comes from the factor of 8 prescale on the 16MHz clock and 256 is the size of the lookup table specified by your LENGTH define. If you start from a frequency you want to synthesize, just use the above equation to solve for the necessary value of OCR2A. Note that since you have to input integer values to OCR2A, you can't really achieve arbitrary frequencies, but you're certainly not locked in to the values given in the supplemental musical note PDF you reference.

So, to solve for OCR2A:

OCR2A = TCNT2_rate / (desiredFreq * wavetableLength);


How many Amps can a Nano Arduino hold for LED project I'm really new at this, and here is my doubt. What if I need to light 120x WS2812B (5v)LEDs (link: LEDs) using an Arduino Nano? if it takes 60 mAh each pixel, the total amount needed should be around 7,200 mA.

Could I use the same 5V/ 8A power supply (PowerSupply) for the Nano board and lights? Is that possible?

Thanks in advance, and sorry my ignorance on this area.

Yes, 120 LEDs * 60 mA = 7200 mA = 7.2A

An Arduino Nano will use 19 mA (Arduino Nano Tech Spec). Of course, if you add a power LED, or other components it will add, but it will likely be less than a few 100 mA. So that totals to max 7.4A.

It's always good to have some headroom which is 0.6A in your case (that's enough).

Actually what's happening is as follows:
- Your 8 mA gives the current the components request
- Your Nano requests 19 mA
- Your LEDs require 7.200 mA.

As long as the voltage is the same (5V for both the LEDs, Nano, and adapter), and the components do not request more than 8 A summed up (with some headroom), the adapter will deliver the current needed. If all components request more than 8 A, than high likely the adapter will break (and possibly the attached components too).


Uni-directional communication between NodeMCU and Arduino spits out garbage I am sending data from ESP8266 (NodeMCU) to Arduino using serial and 9600 baud rate on both sides. Since it is uni-directional and from NodeMCU to Arduino, I am not using a voltage regulator and I have connected tx (Software Serial) of NodeMcu to Rx of Arduino. I've connected the usb of nodeMCU to my computer. I've done the same thing to power Arduino.

Here is some sample code on NodeMCU:

#define Arduino_RX 4 // D2
#define Arduino_TX 5 // D1
SoftwareSerial ArduinoSerial(Arduino_RX, Arduino_TX); // RX | TX

void setup() {
  Serial.begin(115200);
  ArduinoSerial.begin(9600);
  delay(10);

  // Connect to WiFi network
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  WiFi.config(ip, gateway, subnet);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");
}

void loop()
{
    ArduinoSerial.println("hi");
    Serial.println("hi");
    delay(1);
}

Code on Arduino

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

void setup() {
  // put your setup code here, to run once:
    Serial.begin(9600);     // communication with the host computer
    ESPserial.begin(9600);
    Serial.println("Ready");

}

void loop() {
  if ( ESPserial.available() )   {
    Serial.write( ESPserial.read() );
  }
}

https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html
Do you GND them via your PC USB? Try connecting their GND as well.
External power could be an issue as well, I am not aware of power consumption of ESP when they do stuff with their WiFi.


AVR (Arduino Uno) Serial.print and Serial.println only printing 1 or 2 chars I first used the Arduino IDE but now I'm using PlatformIO which is awesome. But I have some big trouble with Serial.print() and Serial.println(). To show this error I have the following example code:

#include <avr/io.h>
#include <util/delay.h>
#include "Arduino.h"
#include "main.h"

int main(int argc, char const *argv[]) {
  Serial.begin(9600);

  section5ex34();

  return 0;
}

void section5ex34() {
  // Initialization
  DDRC = 0b00000100; // Port C2 as output and the rest (including Port C3) as input. (Port C2 is used for a led that indicates when en bit is being read)

  uint8_t b = 0b00000000;

  // here the code reads bits from PORTC3
  for (int i = 0; i < 8; i++) {
    _delay_ms(1000);
    PORTC |= _BV(PORTC2); // Make Port C2 high (indicates a bit will be read)

    if ((PINC & (0b1 << 3)) != 0) {
      b |= (1 << i);
    }

    _delay_ms(100); // Wait for the user to prepare the next bit (because this is now done by hand)
    PORTC &= ~_BV(PORTC2); // Then make Port C2 low
  }

  Serial.println(b, HEX);
}

When I have the code like this, it prints the right Hexadecimal value corresponding with the 8 read bits.

When I add Serial.println("test"); after the print, it doesn't print that.

Or when I change Serial.println(b, HEX); to Serial.println(b, BIN); it prints 11.

When I replace those 2 prints with Serial.println("Hi test test."); it prints Hi, so it seems like it can only print 2 characters.

When I add Serial.println("Hello world . hello . hi"); four times after Serial.begin(9600);, it prints Hello world . h and nothing more. So here it seems like it can print more than 2 characters, but not all. If I wait a few seconds it adds ello to this, so it says Hello world . hello.

In the initial code, when I replace the if-statement with

if ((PINC & (0b1 << 3)) != 0) {
  b |= (1 << i);
  Serial.println("1");
} else {
  Serial.println("0");
}

and when the input is connected to 5v (so high) it prints a 1 once and nothing else, not even a hexadecimal value when the reading is finished.

This problem drives me crazy.

I have an Arduino Uno and use a baudrate of 9600 , 8,N,1.

I hope someone can help me out with this.

You have two issues here:

The first is that you are using the Arduino core library and failed to
initialize it. This is done automatically if you rely on the core's
supplied main(), i.e. you stick with the setup()/loop() style of
coding. If you write your own main(), you should start by calling
init() to initialize the core.

Edit: In this particular instance, you could get away by just enabling
interrupts with sei(). But I consider it good practice to initialize the
core if you are ever going to use it.

The second issue is the abrupt termination of main:
Serial.print() and println() do not really print to the serial port.
Instead, they put the characters to be printed in the output buffer, and
let an interrupt take care of actually sending them through the UART.

Your program ends with

return 0;

This will stop it. It will stop the whole program, including
interrupt-driven tasks. So you will see whatever characters did make it
to the UART, and nothing more.

If you instead end the program with and endless loop

for (;;) ;

it should work as expected.


Trying to get my mega 2560 to work for my 3d printer Trying to pit marlins v2non this board and it gives me an error and I have no idea what to do

Arduino: 1.6.10 (Windows 10), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

Sketch uses 85,558 bytes (33%) of program storage space. Maximum is 253,952 bytes.
Global variables use 3,606 bytes (44%) of dynamic memory, leaving 4,586 bytes for local variables. Maximum is 8,192 bytes.
avrdude: ser_open(): can't open device "\\.\COM4": Access is denied.

avrdude: ser_drain(): read error: The handle is invalid.

avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer
the selected serial port avrdude: stk500v2_getsync(): timeout communicating with programmer
 does not exist or your board is not connected

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

COM4 ... assuming it's a windows host, then?

All those errors may be because the COM port specified doesn't exist. (changed and/or not seen)

0.) Has this mega ever had a sketch uploaded successfully before this? (for anything)

1.) Have you verified within the arduino IDE that COM4 is showing up in the ports menu?  (Tools => Ports)

2.) Did you plug the arduino into a different USB port?  (sometimes when it's re-recognized it'll assign a different COM port)

If it's changed COM port, then (obviously) change the port designation in the IDE.

Try switching it to a different USB port and waiting for device manager to recognize it.  If that doesn't work and the mega worked before update the question with the above info and we'll try again.


Self answering a Intercom and playing louldy for person to response We have two labs - one in 1st floor and other at 2nd floor. We are connected by intercom - both the labs has one device each. The issue is that the person who sits near the intercom is busy through out day answering the intercom and reaching out to the person for whom the call is made for.

This is very tiresome and hence I wish to automate this. I have an Arduino Mega 2560 board. My plan is to make Arduino receive the call ask for the person whom the caller is reaching out and play the name loudly over speaker in all rooms of labs (to attended the phone). If the user does not turns up even after 3 repeated times of calling - disconnect the call. If the user answers the phone by picking up the receiver then turn the conversation speaker mode off until call has not ended.

I have Arduino Mega 2560 board which has 4 serial ports but I am not user what would be the circuit to make this functionality workable? What are the extra h/w required and concept of its implementation.

Let's try to break it down to several components:

Interfacing with POTS (Plain Old Telephony System):
There is a nice article by Joe Doll describing how to interface an Arduino and POTS. POTS involves high voltage during both idle and ringing time (48 V DC, superimposed 90 V AC) and the circuit itself is mostly analog. You can find the required parts and their values in his article, which goes down into the nasty details in a spectacular fashion. Here is the analog circuit, involving the Arduino, from his post:

Consider that there are other projects performing similar task in a different manner, like this one, and this one which specifically explains how to record sound from an old rotary phone.

Play/Record sound from Arduino Mega 2650:
There are many projects that describe how to Play or Record sound using Arduino. Most involve a SD card to store the wav files. There is also the option of an MP3 shield, that comes with a pre-built SD card slot, such as this one. They are fully documented and are easy to interface with.
Code that encapsulates the Logic:
Here you could decide how many times the Arduino should play the recorded name, and what happens if the user won't answer. The disconnection will be done utilizing the POTS interface you created in bullet #1. In addition, you should handle the logic of what happens when the user does answer. It is not clear what you mean by 'receiver', but if you plan to have a remote extension or similar, some extra work will be required.

As a side note, it might be easier to create/re-use a walkie-talkie kind of wireless communicator, accompanied by an Arduino, to signal or broadcast the names of the people called. This might not include reuse or interfacing with the current intercom device, but by thus I believe it will make development easier and faster.


max current while using a shift register In arduino's official page about ShiftOut https://www.arduino.cc/en/Tutorial/ShiftOut, a drawing with two 74HC595 powered by the arduino board, is displayed.

Since the resistors are 220Ω, the total current should be 5/220x16 = 0.36A which exceeds the maximum total current of 0.20A for the arduino device.

So, could someone turn on simultaneously 16 LEDs using two shift registers without damaging the device?

Thank you

0.20A is not the maximum current for an Arduino device.  0.20A is the maximum current for the chip that is on the Arduino.  Thus it is only relevant to devices that are directly connected to the Arduino's IO pins (that connect direct to the chip).

The shift registers take their own power from the +5V pin, which is limited to between 500mA and 800mA depending on how you power your board.  Each shift register has its own power limits that are completely separate to the Arduino's main chip's power limits.


Trying to instantiate a DS3231 real time clock within a library I'm trying to write a library encapsulating things that I do with a DS3231 real time clock. I have managed to compile a sketch using the library, but it apparently blows up when attempting to call clock methods such as getTime().

Header:

// JBP_DS3231.h
#ifndef __JBP_DS3231_h__
#define __JBP_DS3231_h__

#include <SD.h>
#include "DS3231.h"
#include "Arduino.h"

class JBP_DS3231
{
  public:
    JBP_DS3231();
    String TimeStamp();
  private:
    DS3231* _realTimeClock;
};

#endif

cpp:

#include <JBP_DS3231.h>
#include <SD.h>
#include "DS3231.h"
#include "Arduino.h"

JBP_DS3231::JBP_DS3231() {
  String thisTime = "";

  _realTimeClock = &DS3231(SDA, SCL);

  Serial.println("About to try to get time from RTC."); // Last line we hear from.

  thisTime = _realTimeClock->getTimeStr();
  Serial.print("Time in constructor is: ");
  Serial.println(thisTime);
}

String JBP_DS3231::TimeStamp() {
  String timeStamp = "";

  Serial.println("In TimeStamp().");
  timeStamp = _realTimeClock->getDateStr(FORMAT_LONG, FORMAT_MIDDLEENDIAN, '/');
  Serial.print("Value of timestamp is: ");
  Serial.println(timeStamp);
  timeStamp.concat(" ");
  timeStamp.concat(_realTimeClock->getTimeStr());
  Serial.println(timeStamp);

  return timeStamp;
}

Script:

const String WHO_AM_I = "JBP_DS3231_library_test.ino";
const    int VERSION = 0;

#include <JBP_DS3231.h>

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

  JBP_DS3231 johnsRTC;
  Serial.println(johnsRTC.TimeStamp());
}

void loop() {
  return;
}

void AnnounceAwakening() {
  Serial.print("Sketch ");
  Serial.print(WHO_AM_I);
  Serial.print(" version ");
  Serial.print(VERSION);
  Serial.println(".");
  Serial.println("");
}

You appear to be providing a pointer to a constructor, not to an object.  Either create a new object with new, or instantiate the object separately and provide the pointer to the object:

_realTimeClock = new DS3231(SDA, SCL);

Better still, extend the existing class and implement your own methods:

clsss JBP_DS3231 : public DS3231 {
    public:
        JBP_DS3231(uint8_t d, uint8_t c) : DS3231(d, c) {
            String thisTime = "";
            Serial.println("About to try to get time from RTC."); // Last line we hear from.

            thisTime = getTimeStr();
            Serial.print("Time in constructor is: ");
            Serial.println(thisTime);
        }

        String TimeStamp() {
            String timeStamp = "";

            Serial.println("In TimeStamp().");
            timeStamp = getDateStr(FORMAT_LONG, FORMAT_MIDDLEENDIAN, '/');
            Serial.print("Value of timestamp is: ");
            Serial.println(timeStamp);
            timeStamp.concat(" ");
            timeStamp.concat(getTimeStr());
            Serial.println(timeStamp);

            return timeStamp;
        }
};

void setup() {
    Serial.begin(115200);
    JBP_DS3231 myRTC(SDA, SCL);
    Serial.println(johnsRTC.TimeStamp());
}

void loop() {
}

(Note: untested)


Changing Uid Using MFRC522 Via Arduino Error Well, I' ve just bought and recieved a MFRC522 rfıd module and done to much research on it. After watching several videos, I sorted out a library for using this module via arduino.
You can click the first link below to be navigated to Miguel Balboa' s github page including the library that I mentioned and example codes written by him using that library. Though I' ve downloaded the zip file, ran such codes as dumpInfo, read and write, unfortunetely I couldn' t made "changeUid" example work. U can reach this example code via the link below as well. My connection is true, I' m sure bout' that  If anybody had faced this kind of problem or knows the solution, their answers will be enough satisfying for me I guess... (By the way, error was this sentance: Are you sure this is a uid changeable card -I was sure, my card was a Mifare 1K card- failure, the card responded as NAK)

link: https://github.com/miguelbalboa/rfid

Search for UID changeable card. The kit included this RFID reader just had a normal RFID card and keychain. You will probably have to buy it yourself. I bought it from aliexpress but I don' t remember which seller. Good Luck! (I mean who read this...)


Would it be feasible to build an arduino that takes 12v on/off signals from a vehicle diagnostic port (1984 pre-OBD)? The vehicle is an AMC eagle, they come with a diagnostic port
I have made a diagnostic tool that lights led lights when signals turn on and off, but it has to be wired in and is bulky. I am wondering if it would be possible to have an arduino plugged in and running off the 12v battery supply (with step-down to 5v) and have it catch the signals and send them over Bluetooth to a computer. Does this sound like it is within the scope of an arduino or am I asking too much? Or is there a better and easier way to do this?

Yes, it is possible. The 12v signals would have to be conditioned for the Arduino to receive them (0 - 12v or maybe 0 - 12-14.5v?). Then the Bluetooth side would be the same as any other Bluetooth data transmission.

So your question comes down to: Is this a fun project that's worth the effort you put into it for the learning experience? Or is this meant to answer a need, and the most practical means to that end is the best means?

Ex: I wanted to know how long / what kind of driving would it take to get my car's oil to full temp (~100C), starting from dead-cold in the winter? I had a thermo-logger I'd built for another experiment, so I taped a sensor to my oil filter (yeah, not the greatest, but quick and dirty) and lead a cable outside the hood, through the driver's window, to the experimental PC board on my dash-board. It wasn't a miserable failure but nothing to be proud of, either.

The solution I settled on was a USD$12.00 OBD port sender and an iPhone app. The results were much better, and while I didn't have the built-it-myself experience, I got the data and the answers I needed.


programming arduino in pure c I'm trying to flash pure c-code to arduino Mega2560 board from linux using avr-gcc & avrdude. Compilation is done , now trying to flash using avr-dude, getting error as "avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00"

I used below command to produce hex file

avr-gcc -mmcu=atmega2560 -DF_CPU=16000000UL led.c -o led.elf

In file included from led.c:3:0:
/usr/lib/avr/include/util/delay.h:95:3: warning: #warning "Compiler optimizations disabled; functions from  won't work as designed" [-Wcpp]
 # warning "Compiler optimizations disabled; functions from  won't work as designed"

And then

avr-objcopy -j .text -O ihex led.elf led.hex

finally for flashing

avrdude -F -V -c arduino -p ATMEGA2560 -P /dev/ttyACM3 -b 115200 -U flash:w:led.hex

FYI: port is correct & RX pin is blinking i.e connection is perfect between computer & board

In file included from led.c:3:0:
  /usr/lib/avr/include/util/delay.h:95:3: warning: #warning "Compiler
  optimizations disabled; functions from won't work as designed"

You should start by fixing this. Simply add -Os to the compiler
command line. This means “optimize for size”, and is the standard
optimization option used with Arduinos.

  avr-objcopy -j .text -O ihex led.elf led.hex

If your copy of avrdude was compiled with libelf (like the one supplied
with Ubuntu is), you don't need this: you can hand your elf file
directly to avrdude.

  avrdude -F -V -c arduino -p ATMEGA2560 -P /dev/ttyACM3 -b 115200 -U flash:w:led.hex

-F tells avrdude to not verify the device signature. -V tells it
to not verify the upload. I wouldn't use any of these options unless
I had a very good reason to do so. -c arduino is wrong: it selects the
upload protocol used by optiboot (used, e.g., in the Uno). The
Mega 2560 uses a different bootloader based on the “wiring”
protocol. I would also add the -D option (disable auto erase) because
I saw the Arduino IDE using it, and because without this option I get
the error:

avrdude: erasing chip
avrdude: stk500v2_command(): command failed

In the end, the upload command ends up being something like:

avrdude -p atmega2560 -c wiring -P /dev/ttyACM3 -b 115200 -D -U led.elf


Problem with shift register I have a problem with the shift register 74HC595.

The sketch I use is able to enable a specific led (8 are connected).

When I enable led 0 to 7 it behaves like normally (they switch on when I enter the numbers).

However, for the led connected to pin 15 (other side of the ic, see layout) it behaves differently.
 When I switch this led on, ALL leds go off. When I retry, nothing happens. When I enable another led, after a short time (but can be seconds) the led for pin 15 is emitting light together with all others which where already enabled.

This seems like a malfunction in the IC (I checked already another led, another cable, another resistor). The only think I haven't checked is moving the IC to another position of the breadboard (that would take a lot of time since I have to rewrite everything). Is it possible I missed something or is the shift register broken?

The code to switch on a led:

void updateShiftRegister()
{
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, LSBFIRST, leds);
  digitalWrite(latchPin, HIGH);
}

where leds are the indices of the leds (0..7).

You cannot directly give an index (0..7) to a shift register if you want the index to represent the LED number to be switched on.
You have to build a table similar to the following:

byte led[8] = {
0b00000001,
0b00000010,
0b00000100,
0b00001000,
0b00010000,
0b00100000,
0b01000000,
0b10000000
};

and later . . .

shiftOut(dataPin, clockPin, LSBFIRST, led[leds]);

where leds is a number 0..7


How do you balance an Arduino quadcopter using calculated gyro values? I was working on an Arduino quadcopter project. I setup all my hardware and was having balancing problems with my software end. I am using an MPU-6050 gyro and accelerometer. I have calculated the angle of the quad in relation to the ground and was trying to implement these values by adjusting the output values to each of the four motors.

Here is some of my code:

    x=(-computedGyroAngleX-3.5)*10;
    y=(-computedGyroAngleY-2)*10;
    esc1.writeMicroseconds(rc_values[RC_CH1]+x-y);
    esc2.writeMicroseconds(rc_values[RC_CH1]+x+y);
    esc3.writeMicroseconds(rc_values[RC_CH1]-x-y);
    esc4.writeMicroseconds(rc_values[RC_CH1]-x+y);

If the quad is leaning forward I increase the power at the front of the quad and reduce it at the back. I do the same for the y axis. But I run into problems when I test out the quad. It flips over to the side or forward. How would I fix this?

That was happening with me too. Check if the weight distribution of the drone is perfect. Lets say if the battery is placed a little more to one side of the frame than the other side, your drone will try to hover from the other side.
The center of gravity should be taken care of when the drone is not balancing properly.


Timer3 Arduino maximum period At the moment I'm trying to learn microcontrollers with Arduino, and have a problem with the timer.

Arduino works at 16MHz clock, and the best prescaler is 1024, which means the timer increments the value every 64 us. Timer 3 is a 16 bit timer, which gives us a maximum time of 64*65535= 4194240, ca. 4s

But what if I want to do a job every 8 seconds? Any idea?

Here's my code:

TCCR3A = 0;
TCCR3B = 0;
TCCR3B |= (1<<WGM32); //CTC
TCCR3B |= (1 << CS32);
TCCR3B |= (1 << CS30);// 1024 prescaler
TIMSK3 |= (1<<OCIE3A);
sei();

You can't - not directly. Instead you do a job at a higher frequency which just counts. When it has counted enough you do your other job.

For instance, you might trigger your interrupt once a second. That interrupt just adds 1 to a count and returns. Unless that count just hit 8, when you reset the count to 0 and run your 8 second routine.


Arduino Servo.h library returns error in compilation I have a problem with Servo library. This is my (very short XD) "code":

#include <Servo.h>

void setup() {
  Servo.attach(9, 554, 2400);
}

void loop() {
  Servo.write(2000);
}

And it returns:

Arduino:1.6.5 (Windows 7), Board:"Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"

sketch_aug24a.ino: In function 'void setup()':
sketch_aug24a:4: error: expected unqualified-id before '.' token
sketch_aug24a.ino: In function 'void loop()':
sketch_aug24a:8: error: expected unqualified-id before '.' token
expected unqualified-id before '.' token

Like there is no included library. What can I do with it ?

Servo is a class not an object. You have to instantiate it, and then call the functions on the instance. For example:

#include <Servo.h>

Servo sv;

void setup() {
  sv.attach(9, 554, 2400);
}

void loop() {
  sv.write(2000);
}

(Unlike some other libraries, it's done this way so that you can use more than one servo at the same time. You'd make one instance for each servo you want to control.)


Serial communication arduino mega and D1 Wemos Mini Can anyone help me connecting arduino mega to D1 Wemos Mini serially? Please let me know most efficient and easy steps to setup a communication.

Using that following tutorial:

https://engineeringprojectshub.com/serial-communication-between-nodemcu-and-arduino/amp/

Following is the circuit diagram:
https://i.stack.imgur.com/oOKwL.png

Apart from ensuring you're wiring TX -> RX and connecting all grounds, you can use SerialTransfer.h to automatically packetize and parse your data for inter-Arduino communication without the headace. The library is installable through the Arduino IDE and includes many examples.

Here are the library's features:

  This library:

  can be downloaded via the Arduino IDE's Libraries Manager (search "SerialTransfer.h")
  works with "software-serial" libraries
  is non blocking
  uses packet delimiters
  uses consistent overhead byte stuffing
  uses CRC-8 (Polynomial 0x9B with lookup table)
  allows the use of dynamically sized packets (packets can have payload lengths anywhere from 1 to 254 bytes)
  can transfer bytes, ints, floats, and even structs!!

Example TX Arduino Sketch:

#include "SerialTransfer.h"

SerialTransfer myTransfer;

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

void loop()
{
  char buff[] = "hi";

  myTransfer.txObj(buff, sizeof(buff));
  myTransfer.sendData(sizeof(buff));
  delay(100);
}

Example RX Arduino Sketch:

#include "SerialTransfer.h"

SerialTransfer myTransfer;

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

void loop()
{
  if(myTransfer.available())
  {
    char buff[40];

    myTransfer.rxObj(buff, sizeof(buff));

    Serial.println("New Data: ");
    Serial.write(buff, sizeof(buff));
    Serial.println();
  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");

    if(myTransfer.status == -1)
      Serial.println(F("CRC_ERROR"));
    else if(myTransfer.status == -2)
      Serial.println(F("PAYLOAD_ERROR"));
    else if(myTransfer.status == -3)
      Serial.println(F("STOP_BYTE_ERROR"));
  }
}


Arduino WiFi/ESP8266 WiFi Password Changed I am working on a project for a friend who is not very tech savvy involving an ESP8266. It will need to be connected to his WiFi network.

The issue is that he occasionally changed the password to his WiFi network. Since I will not be able to access this device at a moments notice, it needs to be able to adapt to a change in the password. Is this possible with the ESP8266, or should I switch to an Arduino WiFi board, or is something more powerful necessary?

The WiFiManager library was written for exactly this purpose.


Global array doesn't get assigned the space it would take up in memory I have this sketch:
const uint32_t len = 65536;
uint8_t arr[len];

void setup() {}

void loop() {}

The length of the array should fit into the dynamic memory. However, when I compile the sketch it says this in the output window:
Sketch uses 10528 bytes (0%) of program storage space. Maximum is 2031616 bytes.
Global variables use 13504 bytes (1%) of dynamic memory, leaving 1034224 bytes for local variables. Maximum is 1048576 bytes.

If I change len to 10, that doesn't change. The compiler is set to "Debug", so it should not get optimized away. This indicates, that the memory isn't actually being allocated. What seems to be the problem here?
I am compiling for the Teensy 4.0, but the output is the same in essence for the Arduino Uno and other boards (with lower memory sizes).

There is no problem here. Only the compiler is a bit smarter than you anticipated. It sees, that you are not using arr anywhere, so it just optimizes it out.
There are two ways to prevent that, if you really want to:

I think you can use flags to tell the compiler, that this shouldn't be optimized out. I'm no expert in this, others might know more about this and add their own answer
You can just start using it.


stop running a certain function when sensor picks up something and return to where it stops? i have a question on how to program a certain sequence for my robot.

lets say if i would to program to make it run from position a to b, i have a sensor attach to it that should it detect x, it would perform an action called y at the position where it detect x, where action y doesnt change its position.

i would like the robot to continue from where it left after performing action y to go towards b. however i do not know how to pause sequence from a to b and continue from where it left off after performing action y. i am controlling only the motor of the wheels so i can only set the speed of the wheels.

is there a pause function in general( not sleep) in c++ and to continue running its lines of code from where it paused?

You can use different ways:

Pause/sleep, don't use this, since it will block other activities
Poll, poll for time, and check every so-many ms what to do.
Timers/Interrupts, every microcontroller has one or more timers which you can use to generate an interrupt to perform an action. The interrupt can change the mode, and in your main program you can check for the mode what to do (go to another position, pick up something etc.

The last one takes a bit more programming, but is the preferred way to easily make changes later on.

There is no 'pause' function in C, but you can of course pause until an interrupt is triggered. In the datasheet of your microcontroller you can read how this can be used.

So in general your loops look like:

loop()
{
   switch (mode)
   {
   case modeMoveAToB:
       ... move from A to B (just a small portion, like 1 cm)
       break;

   case modeActionY:
       ... Perform action Y
       mode = modeMoveAToB;
       break;
   }

   if (SensorTriggered)
   {
      mode = modeActionY;
      SensorTriggered = false;
   }
}

In the trigger interrupt you set SensorTriggered to true.

Make sure that the modeActionY does not take long, so let it move e.g. 1 cm, so the sensor (SensorTriggered) is checked every 1 cm. If you need other actions, just add them in the case statement. And make the inside of each case statement a function, so you can easily reuse it later and/or keep the functionality clearly divided.


Trouble initializing a struct array The goal for this is to create a struct that includes a name, ID, fileName, and a boolean, then create an array of that structs.
Here's what I came up with:
struct Amiibo
{
  char *aName{};
  char *ID{};
  char *AudioFileName{};
  bool alreadyPlayed{false};
};

Amiibo amii[20] = {

      {"Mario","A5005B00","MARIO",false},                     //0
      {"Meta Knight","A5 00 02 00","MK"},                     //1
      {"Inkling", "A5 00 05 00","INK"},                       //2
      {"Donkey Kong","A5 00 01 00","DK"},                     //3
      {"Lucas","A5 00 0A 00","LUCAS"},                        //4
      {"Duck Hunt", "A5 00 08 00","DUCKH"},                   //5
      {"Ocarina of Time Link","A5 00 01 00","OOTL"},          //6
      {"Breath of The Wild Link","random","BOTWL"},           //7
      {"8-bit Link","random","8BITL"},                        //8
      {"Toon Link","random","TOONL"},                         //9
      {"Mr. Game and Watch","random","GANDW"},                //10
      {"Falco","random","FALCO"},                             //11
      {"King Dedede","random","DEDEDE"},                      //12
      {"Mewtwo","random","MEWTWO"},                           //13
      {"Captain Falcon","random","CAPF"},                     //14
      {"ROB","random","ROB"},                                 //15
      {"PAC-MAN","random","PACMAN"},                          //16
      {"Cloud","random","CLOUD"},                             //17
      {"Ness","random","NESS"},                               //18
      {"Ryu","random","RYU"}                                  //19

};

This gives me the following error:

error: could not convert '{"Mario", "A5005B00", "MARIO", false}' from '' to 'Amiibo'

And the same error for all the other elements of the array.
I tried changing amii[20] to a pointer using *amii[20]. That got me this error:

braces around scalar intializer for type "Amiibo"

I'm not sure what to make of that, since I'm fairly certain this isn't scalar type.
I'd really just like to make a struct array so I can cycle through these at random using a random seed. It shouldn't be that difficult, yet I'm running up against a wall. I'd appreciate any advice you all have to give. Thanks.

If you use default values in struct declaration, you have to define also constructors for setting specific elements:
struct Amiibo
{
  const char *aName{};
  const char *ID{};
  const char *AudioFileName{};
  bool alreadyPlayed{false};

  Amiibo() = default;  // default implementation for default constructor

  Amiibo(const char* name, const char* id, const char * audio)  // constructor with three c strings as parameters
  : aName{ name }
  , ID{ id }
  , AudioFileName{ audio }
  { ; }
};

Amiibo amii[] = {
      {"Mario","A5005B00","MARIO",false},                     //0
      {"Meta Knight","A5 00 02 00","MK"},                     //1
      {"Inkling", "A5 00 05 00","INK"},                       //2
      {"Donkey Kong","A5 00 01 00","DK"},                     //3
      {"Lucas","A5 00 0A 00","LUCAS"},                        //4
      {"Duck Hunt", "A5 00 08 00","DUCKH"},                   //5
      {"Ocarina of Time Link","A5 00 01 00","OOTL"},          //6
      {"Breath of The Wild Link","random","BOTWL"},           //7
      {"8-bit Link","random","8BITL"},                        //8
      {"Toon Link","random","TOONL"},                         //9
      {"Mr. Game and Watch","random","GANDW"},                //10
      {"Falco","random","FALCO"},                             //11
      {"King Dedede","random","DEDEDE"},                      //12
      {"Mewtwo","random","MEWTWO"},                           //13
      {"Captain Falcon","random","CAPF"},                     //14
      {"ROB","random","ROB"},                                 //15
      {"PAC-MAN","random","PACMAN"},                          //16
      {"Cloud","random","CLOUD"},                             //17
      {"Ness","random","NESS"},                               //18
      {"Ryu","random","RYU"}                                  //19
};

Btw on the older AVRs all those strings will resides also in memory


How to properly use volatile variables in Arduino? I was doing a small project with an Arduino Uno. It involved interrupts as I am using encoders to measure how much the differential wheel system moves forward. My robot moves only forward. So I use only a single channel from each encoder. Here are my two interrupt routines:

ISR (INT0_vect){

      encoderRPos = encoderRPos + 1;

}

ISR (INT1_vect){

  encoderLPos = encoderLPos + 1;

}

The variables encoderRPos and encoderLPos are of type volatile int. I understand that the variables which undergoes change in any interrupt routine need to be of type volatile. This is to warn other parts of the code that use these variables that it may change anytime.

But what happened in my code was a bit strange and I could not explain it. Here is how I compute the distance moved by the left wheel:

  #define distancePerCount 0.056196868
  float SR = distancePerCount * (encoderRPos - encoderRPosPrev);
  float SL = distancePerCount * (encoderLPos - encoderLPosPrev);

  encoderRPosPrev = encoderRPos;
  encoderLPosPrev = encoderLPos;

But when I print the following on my serial monitor, I notice an anomaly:

If you look at the third column, (SL) it's value is too high just for some time. This is upsetting all my calculations.

The only clue I can get it, if I take the value of SL that I got (3682), which is always a constant, and calculate back (encodeLPos - encoderLPosPrev), I will get 65519.66, which is close to the max value of unsigned int. Which means (encoderLPos - encoderLPosPrev) is causing an overflow while both the values whose difference is taken is somewhere around 5000 only!

And I managed to solve it. It was by luck. This is how I modified the code:

  static int encoderRPosPrev = 0;
  static int encoderLPosPrev = 0;

  int diffL = (encoderLPos - encoderLPosPrev);
  int diffR = (encoderRPos - encoderRPosPrev);

  float SR = distancePerCount * diffR;
  float SL = distancePerCount * diffL;

  encoderRPosPrev = encoderRPos;
  encoderLPosPrev = encoderLPos;

I can't comprehend what has happened. Is there something about volatile variables that I should have known about?

Update: Here is the entire code if you ever want to take a look. And it's working very well after changing it to what was suggested in the accepted answer.

You need to learn about critical sections.

What is probably happening is that the variables are being changed by the interrupt routines mid-way through the calculations. Your 'fix' reduces the time spent doing the calculation with the volatile variables thus making it less likely that there is a collision.

What you should do is copy the volatile variables to local variables with interrupts disabled for that brief period.

cli();
int l = encoderLpos;
int r = encoderRpos;
sei();

Because the Arduino is an 8 bit CPU it takes multiple assembly instructions to perform mathematical operations on 16 bit values. Floating point is even worse using many many instructions for a simple addition. Division and multiplication use considerably more. An interrupt has plenty of opportunity to fire during that list of instructions. By doing an assignment like that and then using the new local variables in your calculations the instructions needed to deal with the volatile variables is kept to an absolute minimum.  By turning off interrupts during the assignment you guarantee that the variables can't ever be changed while you are using them. This snippet of code is called a critical section.


Trying to send data to the server and AT+CIPSEND not working correctly Sending data to the server(thingspeak.com/184.106.153.14) with AT commands on serial monitor works fine but whenever i upload the sketch ,the following always return false if(Serial.find( ">" ) ). I am not sure if AT+CIPSEND is not working correctly or what. I am using Arduino with ESP8266. Any help will be appreciated.Thanks you in advance. Here is my code.

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

  #define SSID "myssid"
  #define PASS "Mypass"
  #define IP "184.106.153.149" // ThingSpeak

  void setup()
  {
   uint32_t baud = 9600;
   Serial.begin(baud);
   softSerial.begin(baud);

   connectWiFi();
   }

   void loop()
   {
    updateTS();
    }

    void updateTS()
    {
    String cmd = "AT+CIPSTART=\"TCP\",\"";// Setup TCP connection
    cmd += IP;
    cmd += "\",80";
    sendDebug(cmd);
    delay(2000);

    String url = "GET /update?key=P55Z0BDASNQBFQKT&field1=15&field2=25\r\n\r\n"; //hard code value 15 and 25
    String stringLength="AT+CIPSEND=";
    stringLength +=String(url.length( ));
    Serial.println(stringLength);
    //delay(10000); I even tried to delay for few seconds

   //Here is where it fails,it jumps to closing the connection
   if(Serial.find( ">" ) )
    {
     softSerial.print(">");
     softSerial.print(cmds);
     Serial.print(cmds);
    }
    else
    {
     sendDebug( "AT+CIPCLOSE" );//close TCP connection
    }

    }

   void sendDebug(String cmd)
    {
      softSerial.print("SEND: ");
      softSerial.println(cmd);
      Serial.println(cmd);
     }

     boolean connectWiFi()
    {
      Serial.println("AT+CWMODE=1");
      delay(2000);
      String cmd="AT+CWJAP=\""; // Join accespoint
      cmd+=SSID;
      cmd+="\",\"";
      cmd+=PASS;
      cmd+="\"";
      sendDebug(cmd);
      delay(5000);
      if(Serial.find("OK"))
      {
       softSerial.println("RECEIVED: OK");
       return true;
      }
      else
      {
       softSerial.println("RECEIVED: Error");
       return false;
       }
     }

Your code looks like you connected the ESP to the hardware serial port, but your comment says otherwise so:

Your sketch isnt working because you're writing to the wrong serial port half the time, and even when you do use the right serial port (softSerial) you're sending garbage along with it.

Serial.println(stringLength); and Serial.find("OK") should be softSerial.println(stringLength); and softSerial.find("OK").

Serial.find( ">" ) should be softSerial.find( ">" ). You should look for '>' in the buffer between the Arduino and the ESP8266 and not the one between the Arduino and the PC.

softSerial.print(">");, softSerial.println("RECEIVED: OK"); and similar statements should not be there at all. They are not commands or arguments to a command so why are you printing them to the ESP? Whenever you write to softSerial, make sure its a command. Dont send your debug messages to softSerial; use Serial instead.

There's no variable called cmds and yet you're printing it to the serial port. Assuming this code compiled, its probably a typo in your question?

Finally, your code structure is unreliable at best, what with all the delays in it and not a single Serial.available() or softSerial.available(), not to mention the abundant usage of Arduino Strings. I suggest you first learn how to read from a serial port and build C strings from the results and then re-design your code again. Majenko's blog is as good a tutorial as any. Or you could download a library like this one that provides an easy API to the ESP8266, shielding you from the mess of AT commands, while providing you with example sketches that already do what you want. Of course, you could choose to go through their library (.cpp and .h files are the place to be) and figure out how they used AT commands with the ESP and then write your own sketch, library or whatever. Good luck.


Arduino not responding I have been using my arduino uno for many months and it worked very well even till today morning but an hour ago I tried to upload a sketch and arduino IDE showed my this "avrdude: stk500_getsysc(): not in sync: resp =0x00" , at first I thought maybe I burned my atmega32 chip but I bypassed reset and gnd with a jumper wire and opened serial monitor and my atmega32 still printing serial data,so problem must be something else,and also my led13 isn't blinking.Is it problem with bootloader?if so how can I reload bootloader in my board without using another arduino?

I'm personally not really in to this RTFM kind of answer, but in this case it really do answer most of your questions about the bootloader part: http://arduino.cc/en/Hacking/Bootloader

About the error, a quick search on SO gives you this: https://stackoverflow.com/questions/24240285/arduino-nano-3-avrdude-stk500-getsync-not-in-sync-resp-0x00


16 bit register addressing through i2c Note: I'm using just the atmega chip and atmel studio. Not exactly a full arduino.

I have been using the atmega168 with a MAX17040 fuel gauge in a project. The I2C interface between the atmel and the fuel gauge is working fine and I am able to read data from the fuel gauge.

Due to the power requirement of the project, the fuel gauge requires its compensation value to be adjusted. This is a 16 bit register, so according to the manufacturer I have to write 0x1234 across address 0x0C and 0X0D in one go. Otherwise the values are discarded.

All the datasheet and online forums talk about 8-bit I2C addressing (which I have working), but instruction on addressing 16 bit register is limited. I was wondering if anyone can help me on this.

My basic code is pasted below. The I2C_start takes care of TWCR, TWDR, etc. It could be something to do with Repated_Start, but not sure.

uint8_t I2C_write_register(uint8_t device, uint8_t address, uint8_t value)
{
    device <<= 1;

    uint8_t ret = I2C_start(device | TW_WRITE);
    if (ret)
        return 1;

    if (!ret)
        ret = I2C_write(address);
    if (!ret)
        ret = I2C_write(value);
    I2C_stop();

    return ret;
}

uint8_t I2C_start(uint8_t address){
    // reset TWI control register
    TWCR = 0;
    // transmit START condition
    TWCR = _BV(TWINT) | _BV(TWSTA) | _BV(TWEN);
    // wait for end of transmission
    while( !(TWCR & _BV(TWINT)) );

    // check if the start condition was successfully transmitted
    if((TWSR & 0xF8) != TW_START){ return 1; }

    // load slave address into data register
    TWDR = address;
    // start transmission of address
    TWCR = _BV(TWINT) | _BV(TWEN)|_BV(TWEA); //|_BV(TWEA) added
    // wait for end of transmission
    while( !(TWCR & _BV(TWINT)) );

    // check if the device has acknowledged the READ / WRITE mode
    uint8_t twst = TW_STATUS & 0xF8;
    if ( (twst != TW_MT_SLA_ACK) && (twst != TW_MR_SLA_ACK) ) return 1;

    return 0;
}

Ahh, was just able to solve it. Essentially, do not use TW_REPEATED_START. Just keep sending data 8 bit at a time. 1 bit at the beginning of each 8 bit will be lost, so make sure you shift them first.

Wire library uses a very similar concept for use with arduino.

uint8_t I2C_write_register(uint8_t device, uint8_t address, uint8_t value, uint8_t value)
{
    device <<= 1;

    uint8_t ret = I2C_start(device | TW_WRITE);
    if (ret)
        return 1;

    if (!ret)
        ret = I2C_write(address);
    if (!ret)
        ret = I2C_write(value);
    if (!ret)
        ret = I2C_write(value2);
    I2C_stop();

    return ret;
}


Use digital pins as analog - Arduino Micro I have an Arduino Micro and I want to use pin 6 and 8 as an analog pin, according to the manual this is possible:

  The Micro has a total of 12 analog inputs, pins from A0 to A5 are
  labelled directly on the pins and the other ones that you can access
  in code using the constants from A6 trough A11 are shared respectively
  on digital pins 4, 6, 8, 9, 10, and 12.

What exactly do they mean by constants? I am aware what a constant is in the scope of programming, however I'm not sure what I should use to assign pins 6 and 8 as an analog pin? I assume I cannot just do an analogRead(6)?

Constants are variables that cannot change. They are constant.

In this case they are variables that have been set up in the board definition files (in pins_arduino.h in case you're interested) and are named just as they have said - A6 through A11.  This complements the existing A0 through A5 that are normally there anyway.

So you just use those names and it chooses the right pin for you:

int val = analogRead(A8);

The definitions of the pins are:

static const uint8_t A0 = 18;
static const uint8_t A1 = 19;
static const uint8_t A2 = 20;
static const uint8_t A3 = 21;
static const uint8_t A4 = 22;
static const uint8_t A5 = 23;
static const uint8_t A6 = 24;   // D4
static const uint8_t A7 = 25;   // D6
static const uint8_t A8 = 26;   // D8
static const uint8_t A9 = 27;   // D9
static const uint8_t A10 = 28;  // D10
static const uint8_t A11 = 29;  // D12

So no you cannot just use the number 8, you have to use A8 which points to pin number 26. The Arduino core then interprets that number as an analog pin (as opposed to the digital pin, which is 8) and performs an analog read on it.


Setting 10 RGB Strips Independently from Single Arduino I want to control 10 different 12V RGB LED strips independently from a single Arduino.

As a clarification - I've setup a bunch of NeoPixels and understand how to wire and control them independently. So now I'm looking to do something similar but rather than set color of individual LED's, I'm looking to set color of LED strips.

I've already done all the research to understand how to use a MOSFET to control a single strip - but that requires 3 PWM outputs on the Arduino board and I don't see any boards that have 3 * 10 = 30 PWM outputs.

Are there existing controllers that can abstract the power conversion and voltage control, so I can just send a color and brightness setting from the Arduino to each strip?

You could use chainable RGB drivers like these:

They are based on the P9813 chip and can be used with the FastLED library.
You can find them on Aliexpress or eBay, if you search for "STM32 rgb".

Wiring:

Example code:

#include <FastLED.h>

#define NUM_LEDS 10
#define DATA_PIN 3
#define CLOCK_PIN 2

CRGB leds[NUM_LEDS];

void setup() {
    FastLED.addLeds<P9813, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
}

int hue = 0;
void loop(){
    for(int i = 0; i < NUM_LEDS; i++) {
        leds[i] = CHSV(hue + i*255/NUM_LEDS , 255, 255);
    }
    FastLED.show();
    delay(20);
    hue += 2;
}


Controll LED Strip with Arduino BLE I'm working on this project where I have interfaced a LED strip (a two wire LED strip) with this Arduino (its not an Uno). I have setup every thing correctly according to this instructable. I'm able to make a simple blinky pattern and I turn it on/off with an Android app I made to communicate with the Arduino using Bluetooth on my phone. Cool.

What I cannot understand is, since the strip is two wired, how should I address individual LEDs on the strip to make more complex patterns? Can I use bit shifts? Reading an article from Makezine (insufficient reps to post more than 2 links), it says that I should connect the strup directly to the output pin. IMO, this will fry the Arduino or in a less virulent sway, not light up the strip in any way.

Addressing individual LEDS on a simple strip with LEDs in series and/or parallel connection is just not possible.
Connecting the strip directly to an output pin is completely nonsense. Forget it.

You need a strip with digital LED controllers populated, as described (for instance) in another link mentioned in your second link: http://www.adafruit.com/products/306

Have a look at this, then I'm sure you will come back with more detailed questions ;-)


Arduino UNO two SoftwareSerial ports communication I am working on a project involving bluetooth and wifi communications. Both of them are wired up to the Arduino and communicate to it using two software serial port.
The scenario is the one in the picture attached.

What I am doing is:

retrieve the sensor value
send it from the BT slave module to the master one (wired up to Arduino)
take it and send it, using AT commands, through the WIFI channel (the WIFI module is a ESP8266-01) to a web server.

The problem is that if I start listening to the BT serial port (BTSerial.listen()) I am not able to properly send the sensor values through the WIFI connection. But if I comment out the lines related to the BT sotware serial, and try to send fixed value to the web server, the sending terminates succesfully.

In my opinion there are some problems with the BTSerial.listen() and WIFISerial.listen() calls, since they are not able to switch from one the the other correctly.

I saw the TwoSerialPort example provided into the Arduino IDE and I tried to apply it into my code but it still not works to me.

Does anyone have a idea which would be the problem? Does anyone already faced with this problem or a similar one?

Hoping to be as much clear as possible, thanks in advance to anyone would help me.

Filippo

[EDIT] Added two code snippets

// This method prepares the AT commands will be send to the ESP8266-01 module in order to upload the values on the web server
void send2server(String ip, int port, String file, int t, int h, int p) {

  String queryString = "temp=";
  queryString.concat(t);
  queryString.concat("&hum=");
  queryString.concat(h);
  queryString.concat("&press=");
  queryString.concat(p);
  Serial.println(queryString);

  // Prepare and exec the AT+CIPSTART command provideing the TCP connection init
  String CIPSTART_cmd = "AT+CIPSTART=\"TCP\",\"" + ip + "\"," + port + "";
  exec_cmd(CIPSTART_cmd, 1000);

  // Prepare the POST request
  String httpPOST_cmd = "POST /";
  httpPOST_cmd.concat(file);
  httpPOST_cmd.concat(" HTTP/1.1\r\n");
  httpPOST_cmd.concat("Host: ");
  httpPOST_cmd.concat(ip);
  httpPOST_cmd.concat("\r\n");
  //httpPOST_cmd.concat("Accept: */*\r\n");
  httpPOST_cmd.concat("Content-Length: ");
  httpPOST_cmd.concat(queryString.length());
  httpPOST_cmd.concat("\r\n\r\n");
  //httpPOST_cmd.concat("Content-Type: text/html\r\n\r\n");
  httpPOST_cmd.concat(queryString);

  // Calculate the POST request length
  unsigned int len = httpPOST_cmd.length();

  // Prepare and exec the AT+CIPSEND statement with the POST request length just calculated
  String CIPSEND_cmd = "AT+CIPSEND=";
  CIPSEND_cmd.concat(len);
  exec_cmd(CIPSEND_cmd, 1000);

  // Exec the HTTP POST request
  exec_cmd(httpPOST_cmd, 1000);

  // Close the connection
  exec_cmd("AT+CIPCLOSE", 1000);
}

// This method execute each AT command in the previuous method
void exec_cmd(String cmd, int delayTime) {
   byte i = 0;

   while(1) {
      Serial.println("invio comando");
      WIFISerial.println(cmd);
      while(WIFISerial.available()) {
         if(WIFISerial.find("OK")) {
            i = 8;
         }
      }
      delay(delayTime);

      if(i > 5)
         break;

      i++;
   }

   if(i == 8) {
      Serial.println("OK");
      //return true;
   } else {
      Serial.println("ERRORE");
      //return false;
   }
}

The problem is the code goes properly till the AT+CIPSEND command, then the POST request is sent but no good feedback arrives, ending with the "ERRORE" error message.

[EDIT 2] Attached serial monitor output
This is the serial monitor output when I execute the skecth. It seems to work properly but it does not upload any value.

This answer provides full details on choosing "good" combinations of hardware and software serial ports.  To summarize:

Use the HardwareSerial port (i.e., Serial) for one of the devices.  You can still use it for debug prints, as long as the device has some kind of command "format".  For example, if commands start with "AT", just make sure that none of your debug prints start with "AT".  It is the absolute best choice.  You would have to disconnect RX pin 0 from the device in order to upload new sketches over USB.
Use AltSoftSerial for the other device.  It is the most efficient software serial port, and it can be used at the same time as Serial.  It only works on two specific pins.
NeoSWSerial is the next best choice, at limited baud rates.  It can be used with the above choices, but transmitting on NeoSWSerial prevents them from receiving.
SoftwareSerial is the worst choice.  Receiving or transmitting on SoftwareSerial prevents all of the above from receiving anything.  It disables interrupts for long periods of time.

UPDATE - Here is the most reliable configuration:

Your code will have something like this:

#include <AltSoftSerial.h>
AltSoftSerial BT; // 8 is RX, 9 is TX

#define WIFI Serial  // 0 is RX, 1 is TX (disconnect 0 to upload new sketch)

void setup()
{
  WIFI.begin( 115200 );
  BT.begin( 9600 );
}

void loop()
{
  if (BT.available) {
    char c = BT.read();
    // do something with the character
       ... save them until '\n' arrives?
         ... then parse some values?

    if (values all received) {
      Serial.print( F("Sending values") ); // this is the WIFI port, but
          //  the ESP8266 ignores this debug print because it doesn't
          //  start with "AT".

      WIFI.println( F("AT+ ...") ); // all the AT commands
          ...
      WIFI.print( btValue1 );    // and the BT values
          ...
    }
  }
}


How to test if PWM mode is working correcly? I d'like to test if the PWM mode is working correctly on the pins of my Arduino Board. Do you know a simple schema to do this ?

There are my options:

The default way to do this is to use an oscilloscope. These can be quite expensive.
Use a logic analyzer if the voltage is logic/binary (0 and 3.3 or 5V). These are very cheap.
The easiest way to know if it works without the devices above, is to lower the speed drastically (using a divider in the software, like 1000 or more to get PWM widths of 100 ms to multiple seconds) and connect the PWM output with a resistor and a LED to GND. If the LED flashes faster, the PWM speed is high, otherwise low. By using a stopwatch you can roughly calculate the PWM speed (taking the divider into account) and after the test remove the divider.
If the PWM is controlled completely from your Arduino (probably not), you can use a software counter and print it out afterwards to see the speed.


Best way to send I2C commands between Arduino and ESP32 I made a board with an Arduino nano and a ESP32 Dev kit. I connected them via I2C with voltage adaptation. I'm using arduino IDE and the related library Wire.h.

I send messages as ascii chars or native bytes from the ESP32 (master) to the Arduino (slave) and all work fine.

I have to take a decision now. I have to implement a simple protocol to send command to the Arduino, in order to ask it do some tasks or in order to ask it to send some data to the esp32 (e.g. the speed of a motor or the state of some sensors and so on).

What I would ask is your suggestion if the simple protocol has to be managed as native bytes (the natural way I2C work) or as string (managed by mean of an array).
I try to explain.

In case of bytes I could send for example FF 0E14 01 to ask arduino to start the motor=FF at the speed=0E14 and direction=01. So the specific command is coded in the first byte.

What I miss is the need or not for a delimiter like "<" and ">" as used in case of string. In case of exchange of native bytes the value of "<" is "busy" in an integer and couldn't be distinguish by the parser. So what delimiter could I use?

On the other hand in case of strings I don't like the necessity to convert number "213" or "1529" in the relative integer. In case of the previous command I could send the string

""

having in mind the first char as command and for this specific command "S" ("S" for example) parsing the following chars until the "," and convert it in a integer and last char as direction (as byte or as char the test is the same).

I don't know... what way do you suggest and in case of native bytes what delimiters?

Thanks.

First, using a byte-value based protocol is the standard with I2C. There is no real reason to go to ASCII encoded data (The reason for doing this with Serial (UART) is normally, that the message is human readable at the PC. This is normally not the case with I2C, since only computers like the Raspberry Pi even have I2C interfaces).

About delimiters: They are only really needed for asynchronous data transfers (as UART)(to frame a full packet/message) or maybe, if you have an unknown transmission size. Both is not the case for I2C (it is a synchronous interface, that already implements transmission packages/message). You can look at the datasheet of any I2C sensor. The standard communication protocol is a command send by the master, then sending/receiving a specific number of bytes with a specific protocol, that defines, which bytes contains which information. Here you don't need a delimiter, because you already know, in what format the data will be send.

Let's take an example from your question: You want the Arduino to report the speed of your motor to the ESP. You implement the first byte of every master write transmission as a command, for example the decimal value 10 as command to report the motor speed. Then you terminate the master write transmission and request 1 byte from the Arduino (since you already know, that the motor speed has 1 byte). The Arduino knows through the command, that it should send the motor speed byte, and the ESP knows, that the byte received will be the 1 byte motor speed.

Now we define the command 11 to report the motor speed and the 3 bytes sensor value. The ESP sends 11 and then requests 4 bytes, as it knows, that the message will be 4 bytes long. The Arduino sends the data and the ESP knows, that the first byte will be the motor speed and the following 3 bytes the sensor value. No delimiter is needed, since the structure of your data is already defined through the implementation of your protocol. Start or end markers for a message are not needed, since I2C already works with distinct message/packets of data (a transmission is started with a START condition on the bus and ended with a STOP condition).

This solution is used for most I2C devices, since it is easier to implement at a low level. At the first glance for us humans it seems easier to use ASCII encoded and thus human readable data. But as you already mentioned, this makes it more complex for microcontrollers (writing parsers for ASCII data is more complex than using binary data on a fixed protocol). Keep in mind, that I2C means "Inter Integrated Circuit", so communication between integrated circuits, not communication between an integrated circuit and a human.

But in the end it is up to you to decide, which protocol you want to use.

As you might not know the concept yet: A Finite State Machine (FSM) is a good way to implement such a communication protocol on both sides. You define a state variable and based on this variable only the corresponding code is executed. You can change the state by changing the state variable.

For example on the Arduino (receiver side): First state could be the command state, where the Arduino waits for an I2C transmission. If a transmission was received, it will read it's first byte. Depending on this byte it will go into a different state, for example into the "Send motor speed" state. There it will prepare everything to send the motor speed to the master, should the master request data from the Arduino.

How to implement a FSM in detail is covered in many tutorials on the web and also in many questions on this side. You can see my answer to this question, where I explained this in more detail.


RFID reader code to identify more than one tag I'm new to using Arduino and I have managed a few changes to this sketch. But I want to check for a second tag if the first one is not correct. I just can't seem to get it to work. I think it would be good if the tag is not a match to ask it to check the next tag and carry on, but I'm not sure how to make this happen.

//RFID Password Typer
//If a matching tag is found, the keyboard types
//CTRL-ALT-DEL, then types the password and presses enter
//Which should log you on to a Windows computer
//Or Lock the computer if you're already logged in

#include <SPI.h>
#include <MFRC522.h>
#include "Keyboard.h"
#include <Mouse.h>

#define RST_PIN 9
#define SS_PIN 10

byte tag[10]={0x64,0xAE,0xDD,0xFC,};
char pswd[]="********\n";      //password, end with just \n
MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
  SPI.begin();              //start SPI
  mfrc522.PCD_Init();       //start RC522 module
  Keyboard.begin();         //start USB keyboard
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);     //LED off
}

void loop() {
  if (!mfrc522.PICC_IsNewCardPresent()){ return; }
  if (!mfrc522.PICC_ReadCardSerial()){ return; }
  for(byte i = 0; i < mfrc522.uid.size; i++) {
    if(mfrc522.uid.uidByte[i]!=tag[i]){ return; }
  }
  mfrc522.PICC_HaltA(); //stop tag so we don't get repeats
  digitalWrite(13, HIGH); //LED on so we know we've got tag match
  Mouse.click();
  delay(1000);
  Keyboard.press(KEY_LEFT_CTRL);
  delay(1000);
  Keyboard.releaseAll();
  Keyboard.press(KEY_LEFT_CTRL);
  Keyboard.press(KEY_LEFT_ALT);
  Keyboard.press(KEY_DELETE);
  delay(100);
  Keyboard.releaseAll();
  delay(300);
  Keyboard.print(pswd);
  delay(100);
  digitalWrite(13, LOW); //LED off
}

here's how I'd do it ... allowing for 4, 7 and 10 byte uid's (which are all possible apparently)

struct tagInfo {
  byte len;
  byte uid[10];
};
struct tagInfo tag[] = { // add your tags here
  // the len is 1, 2 or 3, for lengths 4, 7, and 10
  // you could just use 4, 7, 10 here and not bother
  // with the len * 3 + 1 calculation later
  // the choice is yours, really
  {1, {0x01, 0x02, 0x03, 0x04}},
  {1, {0x02, 0x03, 0x04, 0x05}},
  {2, {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}},
  {1, {0x02, 0x02, 0x02, 0x02}}
};
const int numtags = sizeof(tag)/sizeof(struct tagInfo);

Then, your loop

void loop() {
  if (!mfrc522.PICC_IsNewCardPresent()) { return; }
  if (!mfrc522.PICC_ReadCardSerial()) { return; }
  int i; // declare before the loop because we want to check the value after the loop ends
  for (i = 0; i < numtags; i++) {
    byte len = tag[i].len * 3 + 1;
    if(len == mfrc522.uid.size) { // 4, 7, 10?
      if(!memcmp(mfrc522.uid.uidByte, tag[i].uid, len)) {
        break; // found an exact match so stop the loop
      }
    }
  }
  if (i == NUMTAGS) { return; } // no matches
  // all good here - run the rest of your code
}


Port manipulation using C code I'm trying to manipulate the ports of Arduino using C code. I have attached an LED to pin 8 and a tact switch to pin 13 (with a pull down resistor). The code works fine, and the results are printed on the screen. So, when the button is pressed, the byte PINB & (1 << PB5) equals 32, or 0b00100000.

However, if I try to use

if( PINB &(1<<PB5) == 32){

or

if( PINB &(1<<PB5) == 0b00100000){

the LED doesn't respond.

Here's the full code:

void setup() {
  DDRB |= 0b00011111;
  Serial.begin(9600);
  }

void loop() {
  Serial.print("PINB &(1<<PB5)");
  Serial.println(PINB &(1<<PB5));

  if( PINB &(1<<PB5) ){
    PORTB |= (1<<PB0);
    }
  else{
    PORTB &= ~(1<<PB0);
    }
  }

What am I missing?

== has higher precedence than &, which means that your comparison will be performed incorrectly. But that doesn't matter, since you don't need to check if the port has a specific value, just if the appropriate bit is set.


How to convert USB to PS/2? Objective: To get my USB keyboard to interface with an Arduino Uno board.

Constraints: I can't afford a USB host shield for now for Arduino. Currently available is a keyboard with PS/2 connector. That example is available here. However, it is silly going for such a keyboard, or, buy a USB to PS/2 converter at the moment.

Challenge: USB has VCC, GND, RX/TX. (Rx/Tx also labelled D+/D- respectively). The parallel port connector has the following:

Where will the D- pin go?

Many USB keyboards (certainly older ones, though almost certainly not wireless ones) are also PS/2 keyboards.  The wiring of the cable is all that differs, and the chip in the keyboard changes its behaviour depending on how it's wired.

A simple USB to PS/2 adaptor is merely a USB socket and PS/2 plug wired together in a certain way:

So that's:

5V to 5V
D- to Data
D+ to Clock
GND to GND

It may work with your keyboard, or it may not. All you can do is try it and see.


Linear Actuator Arduino Control Update:

Here is my first try based on the code I found and it did not work.
The first time I uploaded it, it move to the "current positional value". But did not do the void loop part. Just holds the positions.

Thanks.

    //Includes
    #include <Servo.h>

    //Defines
    #define LINEAR_1_100PIN 11        //Linear Actuator Digital Pin
    #define LINEAR_2_100PIN 6      //Linear Actuator Digital Pin

    String msg;

    //max/min pulse values in microseconds for the linear actuators
    #define LINEAR_1_100_MIN      1050  //
    #define LINEAR_1_100_MAX      2000 //
    #define LINEAR_2_100_MIN  1050     //
    #define LINEAR_2_100_MAX  2000    //

    Servo LINEAR_1_100, LINEAR_2_100;  // create servo objects to control the linear actuators
    //int knobValue, sliderValue;  //variables to hold the last reading from the analog pins

    int linear100Value_1 = 1051;   //current positional value being sent to the linear actuator.
    int linear100Value_2 = 1051;  //current positional value being sent to the linear actuator.

    int speed = 10;

    void setup()
    {
      //initialize servos
      LINEAR_1_100.attach(LINEAR_1_100PIN, LINEAR_1_100_MIN, LINEAR_1_100_MAX);      // attaches/activates the linear actuator as a servo object
      LINEAR_2_100.attach(LINEAR_2_100PIN, LINEAR_2_100_MIN, LINEAR_2_100_MAX);  // attaches/activates the linear actuator as a servo object

      //Analog pins do not need to be initialized

      //use the writeMicroseconds to set the linear actuators to their default positions
      LINEAR_1_100.writeMicroseconds(linear100Value_1);
      LINEAR_2_100.writeMicroseconds(linear100Value_2);
    }

    void loop()
    {
   LINEAR_1_100.write(90);
   delay(1000);
   LINEAR_1_100.write(0);
   delay(1000);
   LINEAR_2_100.write(90);
   delay(1000);
   LINEAR_2_100.write(0);
   delay(1000);
    }

Old Question:

I am trying to make the code described in this tutorial:

http://learn.robotgeek.com/demo-code/118-arduino-linear-actuator-tutorial-analog-direct-control-of-small-linear-actuator.html

https://github.com/robotgeek/firgelliDirectControl/blob/master/firgelliDirectControl/firgelliDirectControl.ino

work with PWM from an Arduino, without the additional board.

So far the Arduino Examples>Servo>Sweep works as I would like to achieve it (delay changed to 30 ms) but very slowly and it does not seem to just go 180 steps out wait 30 ms and 180 steps in again. It sometimes moves twice in one direction. If I change the steps from 1 to 5 the servo does not move anymore (I expected it to go faster).

With the code above I understand I can control the servo with a Knob or Slider, but I would like to understand how I can control this Linear Actuator Servo with PWM from an Arduino PMW Pin (e.g. 11) and change the speed. Finally I would like to make the Servo consistently go x amount of steps out, wait for x ms and the same amount back in again.

Most importantly I would like to make sure it always ends at position 0, and that it does not accumulate errors.

Thank you for any help.

About being sure about returning to position 0 this is not a problem. You are not actually controlling anything with your PWM. You are only sending a signal to the IC inside the servo to tell it where to move the actuator. That IC knows in what position the actuator is located in any moment, usually using some kind of encoder (it's called a closed loop system) and it will make sure that it will move back exactly to 0 whenever you tell it to move to 0.

If you want to make things clearer you can use write method to send value to the servo.

void Servo::write(int value)
{
  if(value < MIN_PULSE_WIDTH)
  {  // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)
    if(value < 0) value = 0;
    if(value > 180) value = 180;
    value = map(value, 0, 180, SERVO_MIN(),  SERVO_MAX());
  }
  this->writeMicroseconds(value);
}

Any value from 0 to 180 will set a position to which servo will move from MIN to MAX possible position. No need for manual calculation of microseconds.

You have to remember that PWM works constantly. If you write for example LINEAR_1_100.writeMicroseconds(1051) this code will set some timers, counters and prescalers inside the ATmega chip on the Arduino board and the value of PWM will be sent constantly until you change it.

So the delay(2000) doesn't stop the PWM signal, and servo remains in constant position.

The issue is here:

LINEAR_1_100.writeMicroseconds(1800);
LINEAR_1_100.writeMicroseconds(1051);

You set the value of 1800 and then immediatelly set value of 1051, but the ATmega didn't even have the time to send the first value to the servo.
Add a delay(1000) after every call of write or writeMicroseconds to allow the PWM to actually be sent to the servo.