How to store values from a sensor inside an empty array? I need to store the value of the distance in the dist array, then calculate the maximun value and print the index associated with this value:

The problem is when starting the nested for inside another for, the servomotor stops working

// Includes the Servo library
#include <Servo.h>

// Array y valores para funcion valor maximo

int max=0;

int angle=0;

int distance=0;

// Defines Tirg and Echo pins of the Ultrasonic Sensor

const int trigPin = 10;

const int echoPin = 11;

// Variables for the duration and the distance

long duration;

//int distance[180];

Servo myServo1; // Creates a servo object for controlling the servo motor

void setup() {

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output

  pinMode(echoPin, INPUT); // Sets the echoPin as an Input

  Serial.begin(9600);

  myServo1.attach(12); // Defines on which pin is the servo motor attached
  }

void loop() {

distance = calculateDistance();
  if (distance <= 15 && distance >=2)
  {

  // rotates the servo motor from 1 to 179 degrees and calculate the distance at each angle

  for(int j=90;j>=0;j--){

  myServo1.write(j);

  delay(30);}

  for(int j=0;j<=180;j++){

  myServo1.write(j);

  int i=0;

  int  dist [i] = {calculateDistance()};

      for (i=0;i=180;i++){           <--------------------------------------

       if (dist[i]>max){
      max=dist[i];
      angle=i;
      Serial.print(angle);
      delay(30);}

  }
      }

  // Repeats the previous lines from 179 to 90 degrees

for(int j=180;j>90;j--){

  myServo1.write(j);

  delay(30);

  }
}
}

// Function for calculating the distance measured by the Ultrasonic sensor
int calculateDistance(){

  digitalWrite(trigPin, LOW);

  delayMicroseconds(2);

  // Sets the trigPin on HIGH state for 10 micro seconds

  digitalWrite(trigPin, HIGH);

  delayMicroseconds(10);

  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds

  distance= duration*0.034/2;

  return distance;

}

int i=0;
  int  dist [i] = {
    calculateDistance()      };

I'm not sure what you are thinking here, but you obviously cannot store data into a zero-length array. You also cannot put a function call to populate an array of variable length.

You need to decide how many elements you need in the array, in advance, and allocate an array of that size.

Maybe more like this:

 int  dist [180];

  for (i=0;i<180;i++){
    dist [i] = calculateDistance ();
    if (dist[i]>max){
      max=dist[i];
      angle=i;
      Serial.print(angle);
      delay(30);
    }

  }

Also, this is wrong in your code:

for (i=0;i=180;i++){

You need to test for < 180 here. Your for loop will assign 180 to i and then check to see if it is non-zero, which will always be true.


Is it wise to use analog input pins to read digital buttons? I am thinking about building a circuit that is literally going to take 11 of the 14 digital pins of an UNO to communicate with an SD card and an external EEPROM chip (EEPROM programmer).

Using 4 shift registers and the SD card, I will have 1 digital pin left.  Well, I'm also reserving pins 0/1 for serial communication.

Anyway, I need to read some external buttons and I have the 6 analog pins that I haven't touched.

I will only need about 4-5 push buttons in my design so they should fit nicely on A0+.

So, my question is, will I run into any issues doing this?  Or, are the analog inputs better left for true analog reading?

Thanks.

The Analog pins are essentially identical in functionality to digital pins when used as digital I/O.

If desired you could "be clever" and use an analog input in analog mode to read multiple keys using one pin. eg using 10k, 22k, 39k, 82k, 150k in series with 5 buttons from V+ to pin and a say 4k7 to ground would result in 5 voltages which were easily distinguished using an analog read. This is a very very old technique indeed and allows far more than 5 keys on one input pin. THere are limitations which can be discussed if required.

R1 ... R5 correspond to buttons 1...5

Vout = V+ x Rb / (Rb + Rbutton)

Example only

Rb = 39k
R1 = 10k
R2 = 22k
R3 = 39k
R4 = 82k
R5 = 150k

Gives

The % of V+ in column 2 when a button is pressed.
The voltage in column 3 with V+ = 5V

Delta-V is the difference between that key and the one below - very ample clearance.


Unable to perform write operation while esp8266 flash operation I have just started working with Arduion project from scratch using esp8266 (AI-cloud inside) black module. Now I'm trying to flash the esp8266 using esptool.py I observed that the esp module gets erased successfully but gives the fatal error while performing write operation.

for more details about the steps I have taken follow the below statments

C:\Users\iSandeep>esptool.py --port COM3 erase_flash
esptool.py v2.3.1
Connecting.....
Detecting chip type... ESP8266
Chip is ESP8266EX
Features: WiFi
Uploading stub...
Running stub...
Stub running...
Erasing flash (this may take a while)...
Chip erase completed successfully in 0.0s
Hard resetting via RTS pin...

C:\Users\iSandeep>esptool.py --port COM3 --baud 115200 write_flash --flash_size=
detect 0 "D:\sw\Arduino\aTTEMPT 4\esp8266-20170108-v1.8.7.bin" --verify
esptool.py v2.3.1
Connecting........_____....._____....._____....._____....._____....._____.....__
___....._____....._____....._____

A fatal error occurred: Failed to connect to Espressif device: Timed out waiting for packet header

Tutorial or instructions followed from here.

Maybe you can try to use ESP Flash Download Tool from here


Looking for SPI documentation I'm trying to use an Arduino as a slave and was searching for examples which I found many. But apart from the examples, I haven't found any documentation explaining many thing that show up in those examples.

For example, I'd like a document that would state what things like the following are:
-SPCR
-SPE
-SPDR
-ISR
-SPI_STC_vect

I'm asking this, because I don't and can't just copy an example and hope that it'll work, I really need to know what I'm doing.

Thank you,
João

You are confusing SPI, a de facto standard, with the Arduino/Atmel hardware support for SPI.

SPCR, SPE and SPDR are registers of the Atmel MCU, part of the hardware support.

ISR is Interrupt Service Routine and SPI_STC_vect is the vector that point to that code. That is where the data received from the cable is read finally.


How to get an angle from two ultrasonic sensors I am building a chair for a special 4 year-old with cerebral palsy, I thought it would be a good idea to add two distance sensors on each arm of the chair to measure the angle at which he presses buttons(a gaming chair).  Normally I would figure this out on my own but I don't have much time to finish so I thought i'd ask the experts.  What's the best way to use to ultrasonic sensors data to produce an angle?

Your question is unclear. You say you want "...to measure the angle at which he presses buttons". I don't know what that means.
If you're using ultrasonic sensors those measure distance. buttons tend to be fixed in place. Maybe you're  talking about having a joystick on the gaming chair? Two-axis joysticks should let you input an X and a y value.
If you're trying to calculate the angle between a pair of ultrasonic sensors and something that is in their "line of sight" (line of sound?) then you'd use trig.
You would have your sensors at a known distance from each other. You'd measure the distance to each sensor, form a triangle out of all 3 distances, and use the law of cosines to calculate the angles.
The formulas from that page are:
cos(C) =  a² + b² − c²/2ab
cos(A) =  b² + c² − a²/2bc
cos(B) =  c² + a² − b²/2ca
(Where upper case letters denote the angles of the triangle at a vertex, and lower-case letters denote the legs of the triangle. See the illustration on that page.)
 SensorA
    \
     \      SensorB
      \       /
       \     /
        \   /
         \ /
          V
        object

(one leg would be the SensorA-to-SensorB distance. Another leg would be the SensorA-to-object distance, and the 3rd leg would be the SensorB-to-object distance.)
However, all of that will only work if the object you are detecting is in the range of angles in which your sensors are able to detect objects, and in the range of distances they provide accurate readings.
Edit:
When I copied the formulas from the source site, the superscripts were lost. I've edited them back so the formulas are more readable.


Writing Data through Pin at certain frequency I have an Arduino UNO which is connected to an KLZ25 board, the Arduino sends an 1MHz Clock at Pin 9 and now I should write the PDM-Data with 1 Mhz at pin 8. But i don't know how to write with such a speed, because if I write in the Loop:

loop{
digitalWrite(1);
digitalWrite(0);
}

I get only a frequency of 36Khz, I know it depends on the count of commands in the loop, but I don't know how to write with a certain frequency in my case 1Mhz.

I get the PDM-Data (pulse density modulation) in form of 1 and 0 from a python script on a Host-PC and now I want to stream the Data with 1MHz to an other developer board which makes further calculation with the PDM-Data. I store the PDM-Data in queues because I have not enough memory to store the whole Data.

Does anybody know how to write PDM-Data with a 1MHz frequency to an output pin ?

If I understand correctly, you want to output a synchronous serial bit
stream at 1 MHz. Something like this:

        ___     ___     ___
clk  __/   \___/   \___/   \___⋅⋅⋅
     ______ _______ _______ ___
dat  __D0__X___D1__X___D2__X___⋅⋅⋅

where the data bits come from the PC.

If you want this to be a continuous bit stream, it will not be easy to
generate on an Arduino Uno.

Receiving the data

Since the data comes from the PC, it comes presumably through the serial
link. You have to account for the fact that this link adds a start bit
and a stop bit to every byte. Thus, you have 10 bits on the wire
for every 8 bits of actual data. Since you have to sustain
1 Mb/s average of actual data, this means that you must configure
the serial port for at least 1.25 Mb/s. However, the only baud rate
higher that 1 Mb/s supported by the Arduino Uno is 2 Mb/s.

Does your PC support this baud rate? Is the communication reliable at
this speed?

If the speed is too high, I would suggest you try to have the PC send
the data as PCM at a lower speed, and have the Arduino handle the
PCM → PDM conversion.

Transmitting the data

This data format is very similar to an SPI transmission. Then, the SPI
hardware port seems like the easiest way to generate it. However, the
SPI transmitter on the Uno is not double-buffered. This means that you
have to wait for the current byte transmission to be finished before
providing the next byte to the SPI hardware. This in turn means that you
will inevitably have small delays between consecutive bytes, and one out
of every 8 clock cycles will be stretched beyond the expected
1 µs. If this unsteadiness is acceptable for your application, then
do use the SPI transmitter. If not, you will have to find another
solution.

The serial port on the Uno has a special mode of operation where it
behaves like a master SPI port. Unlike the actual SPI port, this port is
double-buffered, which makes it possible to send a continuous bit stream
with a steady clock. The problem is, you cannot use this mode for
transmission and at the same time use the serial port receiver in its
regular asynchronous mode. Thus you will not be able to receive the data
from the PC when using this mode. If you can manage to route the
PC → Arduino communication through SPI, this mode of operation
of the serial port may be a good choice.

If none of the options above works for you I suggest, as last resort, to
generate the bitstream entirely by software. The timings are tight, as
each level of the clock has to be held for only 8 CPU cycles. But
it is likely doable in hand-written assembly, provided that interrupts
are disabled. Here is roughly how I may try to do that:

    in output, _SFR_IO_ADDR(PORT_OUT)   ; save a copy of the port reg.

loop:
    lds data, _SFR_MEM_ADDR(UDR0)       ; load data from USART

    ; output bit 0
    andi output, ~_BV(1)                ; clear clock bit
    bst data, 0                         ; save data[0]
    bld output, 0                       ; load it into output[0]
    ; no delay needed here
    out _SFR_IO_ADDR(PORT_OUT), output  ; output
    ori output, _BV(1)                  ; set the clock bit
    delay 6                             ; assumed to be a macro
    out _SFR_IO_ADDR(PORT_OUT), output  ; output

    ; output bit 1
    andi output, ~_BV(1)                ; clear clock bit
    bst data, 1                         ; save data[1]
    bld output, 0                       ; load it into output[0]
    delay 4
    out _SFR_IO_ADDR(PORT_OUT), output  ; output
    ori output, _BV(1)                  ; set the clock bit
    delay 6
    out _SFR_IO_ADDR(PORT_OUT), output  ; output

    ; etc...

    rjmp loop

The code above assumes the UART is synchronized with the output stream,
which will likely not be the case in reality. Your real application may
then be more complex, and you will have to make that extra complexity
fit within the delay slots above.

Note that if you handle the PCM → PDM conversion on the
Arduino the resulting code may end up being simpler, as you will be able
to read the UART at every loop iteration without worrying about
synchronization. I have written a program that does something very
similar a while ago, and I just pushed it to GitHub for you to take a
look: avr-dac: Turn an AVR into a 1-bit D/A converter. Note
that this program is meant to be usable on AVRs without a hardware UART.
It expects the PCM data to be fed in the fashion of a shift register.
Using the UART would make the program simpler.


Understanding SevSeg I need to write a library for a display I created with eight segments. So, I decided to try to use SevSeg (https://github.com/DeanIsMe/SevSeg) as a starting off point. It can't be that different, right?

Well, I think I have hit a roadblock that indicates I must basically do everything from scratch. Here is how the information on what segments correspond to letters are stored in SevSeg:

 // The codes below indicate which segments must be
//illuminated to display each number.

static const byte digitCodeMap[] = {
  //     GFEDCBA  Segments      7-segment map:
  B00111111, // 0   "0"          AAA
  B00000110, // 1   "1"         F   B
  B01011011, // 2   "2"         F   B
  B01001111, // 3   "3"          GGG
  B01100110, // 4   "4"         E   C
  B01101101, // 5   "5"         E   C
  B01111101, // 6   "6"          DDD
  B00000111, // 7   "7"
  B01111111, // 8   "8"
  B01101111, // 9   "9"
  B01110111, // 65  'A'
  B01111100, // 66  'b'
  B00111001, // 67  'C'
  B01011110, // 68  'd'
  B01111001, // 69  'E'
  B01110001, // 70  'F'
  B00111101, // 71  'G'
  B01110110, // 72  'H'
  B00000110, // 73  'I'
  B00001110, // 74  'J'
  B01110110, // 75  'K'  Same as 'H'
  B00111000, // 76  'L'
  B00000000, // 77  'M'  NO DISPLAY
  B01010100, // 78  'n'
  B00111111, // 79  'O'
  B01110011, // 80  'P'
  B01100111, // 81  'q'
  B01010000, // 82  'r'
  B01101101, // 83  'S'
  B01111000, // 84  't'
  B00111110, // 85  'U'
  B00111110, // 86  'V'  Same as 'U'
  B00000000, // 87  'W'  NO DISPLAY
  B01110110, // 88  'X'  Same as 'H'
  B01101110, // 89  'y'
  B01011011, // 90  'Z'  Same as '2'
  B00000000, // 32  ' '  BLANK
  B01000000, // 45  '-'  DASH
};

As you can see this is a one dimensional array of 8-byte binaries that encode the segment. I don't understand the purpose of the B0 at the beginning of each byte. Could I use the 0 column to encode my eighth segment?

Am I right to assume this will change everything about the code and maybe I should start from scratch with a 2-D array?

This is roughly what I want:

//  ABCDEFGH  Segments      8-segment map:
  11000011, // 0   "0"       A BBBBB H
  10000000, // 1   "1"       A C   D H
  01011010, // 2   "2"       A C   D H
  11101010, // 3   "3"       A  C D  H
  00110101, // 4   "4"       A  E F  H
  01011010, // 5   "5"       A E   F H
  11101110, // 6   "6"       A E   F H
  01011000, // 7   "7"       A GGGGG H
  01111110, // 8   "8"
  01100101, // 9   "9"
  11111101, // 10  "A"
  10001110, // 11  "b"
  11000010, // 12  "C"
  00001111, // 13  "d"

What data type should I use for the array? Would byte work since I'm not using the B0?

Thanks.

I don't understand the purpose of the B0 at the beginning of each byte.

That's just Arduino's rather weird way of doing binary constants. For example, in the file binary.h are lines and lines of stuff like this:

#define B1011 11
#define B01011 11
#define B001011 11
#define B0001011 11
#define B00001011 11
#define B1100 12
#define B01100 12
#define B001100 12
#define B0001100 12
#define B00001100 12

A better way is to use standard C++ constants, eg.

0b00001100

instead of:

B00001100

  Could I use the 0 column to encode my eighth segment?

Yes, they are just bytes, so you can use all 8 bits.


A beginner lost at sea, Arduino looking at the sun I am working on trying to make a LED strip respond to natural Light levels for a sculpture. I have reached a problem in trying to get the code to work when sending PWM to the light strip. Thank you for any suggestions!

const int analogInPin = A0;
const int analogOutPin = 9;

int sensorValue = 0;
int outputValue = 0;

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

void loop() {
  sensorValue = analogRead(analogInPin);
  outputValue = map(sensorValue, 0, 1023, 0, 500);
  analogWrite(analogOutPin, outputValue);
  Serial.print("sensor = ");
  Serial.print(sensorValue);
  Serial.print("\t output = ");
  Serial.println(outputValue);
  delay(2);
}

I am using an NTE 2908 N-channel.

You'd better post also the schematic, but I'm pretty sure you just messed up the circuit.

I think you just put the ground connection for the LED strip in the wrong pin (AREF). If you look, the top-most blue wire goes to the third pin from above in the right connector (which is AREF) instead of the fourth one (which is GND). Move this and it should work

Otherwise, put the schematic on the question


How to measure nitrogen flow through a tube? I am looking for a simple way to detect nitrogen gas flow through a tube. I don't even need any sort of precision, just really need to know if flow exists or not.

What are some options I could pursue to easily measure this with the arduino?

You can use a pressure sensor for gas and measure the pressure differential between two points and if there is a large pressure differential then you know a flow exists.


How to subtract micros()? I am attempting to calculate the time between pulses by comparing the micros() timestamp. I understand that you cannot just simply subtract unsigned longs, but I cannot understand what the alternative for it is.

Below is a simplified version of code. On pin 6 I receive 2ms long pulses every 2ms comparing the times returns "-19728". I'm planning to make the pulses much shorter once I figure out this math problem.

Site note: I'm using pulses to make two Arduinos send simple data via digital pins.

Thanks you.

int pinReceiver = 6;
int val = 0;
int isReceiving = 0;
int pauseLength = 0;
unsigned long timeStart = 0;

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

void loop() {
  noInterrupts();
  val = digitalRead(pinReceiver);

  if(val==HIGH){
    if(isReceiving==0){ //Pulse begins
      isReceiving = 1;
      pauseLength = micros() - timeStart;
      Serial.println(pauseLength);
    }

  } else {
    if(isReceiving==1){ //Pulse ends
      isReceiving = 0;
      timeStart = micros();
    }
  }
  interrupts();
}

Long to Integer conversion will overflow the value and you'll get values in negative numbers.

Define the pauseLength as unsigned long to make it work.


Connecting button as PC usb input via arduino I have button with 2 leads (one red and one black). I would like to connect it to PC which allows a press of the button to register as a key press on the computer. I understand an interface board is necessary and I currently have an arduino UNO board with me with a USB cable out to the computer.

Can someone guide me in the right direction regarding soldering of the 2 wires to the board and the relevant sketches for the board itself?

Thank you very much

Regards
Ben

This is a great tutorial on exactly what you want to achieve:

http://mitchtech.net/arduino-usb-hid-keyboard/


How can I use both ultrasonic and IR sensor and ultrasonic sensor at ones with Arduino I  want to use both the ultrasonic sensor and IR sensor with Arduino + motors for a car project. Will I have to do any kind of multithreading on Arduino, or is it something else

Arduinos don't do multithreading. There are a number of attempts at implementing such things, but they're a waste of time and resources.
Instead you need to get into the habit of two things:

Write non-blocking code
Make use of the internal hardware peripherals when possible

The motors, using the hardware PWM, are very much "fire and forget" - set them going and you can forget about them until you want to change their speed or direction.
Ultrasonic sensors can be made both more accurate and more "in the background" by using the Input Capture peripheral of the Arduino.
IR sensors (I assume you mean proximity sensors) are usually either just like a button or a potentiometer - you just read them when you want to know what it's doing.
It's your task to learn how to fit all that together into a single program that reacts to the inputs in the way you want and control the motors in the right way.


Field Hockey Ball Tracker I'm brand new to development and planning a project with my daughter to track speed and time in motion of a ball.

Example, ball is at rest. It is then put into play, timer starts, and speed is tracked until ball is at rest. Is is possible to get accurate data with relatively inexpensive sensors?

Data would look like:
Moved 19 consecutive seconds, average speed during that time=33mph.

Direction, elevation, acceleration changes, etc. would be ignored at this time. To start we just want average speed over time in use. We're having a bit of trouble deciding between accelerometers vs gyro vs magnetometer (or combination)

Any assistance (even links to where to learn) would be greatly appreciated

An accelerometer is the way to go. There will be a fair amount of math to go thru in order  to convert the acceleration value into speed. I can't explain it better than this answer.

An gyro would give you the angular rate on the ball and the magnetometer could give you the ball orientation relative to the magnetic north.


ESP8266 GET method error I am working on ESP8266 and I want to send a GET request with AT command to my localhost but I failed every time. Can you help me solve this problem please? Thank you for interest!
I attached my terminal code and my code:

#define ag_ismi "SUPERONLINE_WiFi_8022"
#define ag_sifresi "rC5YGNYebuCf"
#define IP "192.168.1.9"

void setup() {
  // put your setup code here, to run once:

  Serial.begin(115200);
  Serial.println("AT");
  delay(3000);
  if(Serial.find("OK")){
    Serial.println("AT+CWMODE=1");
    delay(2000);
    String baglantiKomutu=String("AT+CWJAP=\"")+ag_ismi+"\",\""+ag_sifresi+"\"";
    Serial.println(baglantiKomutu);
    delay(5000);
  }
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(60000);
  Serial.println("AT+CIPMUX=1");
  Serial.println("AT+CIPSTART=\"TCP\",\"192.168.1.9\",8000");
  delay(1000);
  String model = "GET /kanbanDB/arduino?model=1 HTTP/1.1";
  //model+="Host: 192.168.1.9:8000\r\n\r\n";
  model+="r\n\r\n";
  Serial.println("AT+CIPSEND=" + String(model.length()));
  Serial.println("\r\n\r\n");
  delay(1000);
  Serial.println(model);
  Serial.println("\r\n\r\n");
  delay(1000);
  Serial.println("");
}

It should be

String model = "GET /kanbanDB/arduino?model=1 HTTP/1.1\r\n";
model+="Host: 192.168.1.9\r\n\r\n";

remove Serial.println("\r\n\r\n"); before Serial.println(model); it is send before GET line

Serial.println("AT+CIPSTART=\"TCP\",\"192.168.1.9\",8000");
String model = "GET /kanbanDB/arduino?model=1 HTTP/1.1\r\n";
model+= "Host: 192.168.1.9\r\n\r\n";
Serial.print("AT+CIPSEND=");
Serial.println(model.length());
delay(1000);
Serial.print(model);
delay(1000);

EDIT:
Remove debug prints to Serial or use SoftwareSerial to connect the esp8266 to Uno. Now the debug prints are sent to esp8266 mixed with AT commands and data. For SoftwareSerial change the default baud rate of the AT firmware.


Problem with deploying matlab simulink mode to Arduino UNO I encounter a problem when deploy matlab simulink model to Arduino UNO

Following shows the error

*The call to realtime_make_rtw_hook, during the after_make hook generated  the following error:
The build failed with the following message: The system cannot find the path specified
The build process will terminate as a result.
The build failed with the following message: The system cannot find the path specified。
Component: Simulink | Category: Block error*

When type >> getenv('path')

ans =

C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;E:\MathWorks\runtime\win64;E:\MathWorks\bin;E:\MathWorks\polyspace\bin;C:\Program Files\MATLAB\R2014b\runtime\win64;C:\Program Files\MATLAB\R2014b\bin;C:\Program Files\MATLAB\R2014b\polyspace\bin;C:\Program Files\Microsoft Windows Performance Toolkit\

I did not see anything wrong with the path. I tried to solve the problem following the "http://www.mathworks.com/matlabcentral/answers/168555-what-does-the-path-in-the-system-cannot-find-the-path-specified-refer-to". However it does not work.

Anyone know how to solve it?

OS:Win8.1 Matlab 2014b 64bit

Right click on your MATLAB shortcut and click "run as administrator". See if helps. Then do all the necessary steps and see if it happens again.

Also test with x86 version. I have seen lots of these kinds of error with x64 version. Always had compiling related issues with MATLAB x64 and Simulink!


Is Arduino Keyboard in Single User Mode Possible? Has anyone had success using the keyboard functionality of any arduino in single user mode of mac computers? I would like to inject keystrokes in single user mode, and have been unsuccessful with the atmega32u4.

OS X requires a "Boot Interface" compatible HID profile for a keyboard to work in single user mode (it has only loaded very rudimentary drivers by that point).  The Arduino doesn't provide that interface, so can only work with the more advanced drivers the OS provides once booted.

You can try setting the "boot interface" flag to 1 in the interface subclass (here, I think, changing HID_SUBCLASS_NONE to HID_SUBCLASS_BOOT_INTERFACE) though I have no clue what the actual effect of that will be given that it's a composite device that may or may not conform to the boot interface standard.


Clock drift - is the precision of the crystal the only culprit? I've a wall clock (sorry, code's a mess, look for updateClockVars) which makes use of the Timezone library (and ultimately Time). Nothing fancy, call millis() every loop; turn to Hrs, Mins, Secs; display on LEDs.

The magnitude of the drift I am seeing on my 2 Arduino Pro Mini - compatible boards - up to ~8% lag, not a typo - blows my mind. Replacing the 16MHz quartz with one bought at a local retailer didn't help much (~33% improvement). Is something else at play here?

The problem is the interaction between the interrupt handler that updates the value for the millis() function and the neopixels show() function.

To maintain the counter for the millis() function a interrupt is triggered approximately every 1.024 ms.

When the show() function is called all interrupts are disabled to get the precise timing needed to send the data to the neopixels.  For a 60 led strip this takes about 1800 microseconds (60 leds * 24 bits * 1.25 us per bit) so at least one interrupt is skipped each time you update the display.

This page has details about how the millis() function works.


RFM95 digital io to control mute on PAM8403 to get rid of hiss while receiving I am building a solution with an ESP32, a PAM8403 amp, a parallel TFT display, and a RFM95 LoRa module. All works great but I want to get rid of the noise that is generated when Lora is in receive mode.
I can do this by pulling pin 12 low on the PAM8403, which mutes all sound. However I have ran out of output pins on my ESP32, and it's too late to use a IO expander as the PCB has been built.
My initial idea was to use the RX/TX pins on the ESP32 when the unit was out of diagnostics mode. However if I can avoid this then that would be great. In my code when I issue Lora.sleep() / Lora.idle() the hissing goes away.
So I started to wonder if I could just trigger the mute function through another logic state that goes low when LoRa is idle and high when sleeping (allowing the mute to deactivate).
I am using the LoRa library by Sandeep Mistry, and I was wondering if I could use DIO1, DIO2, etc. as an IO PIN to control mute. If not, is it possible to use any of the already connected pins to behave in the desired way?
Thanks all in advance!

No, there is no way you can use the DIO pins to indicate sleep mode. They can only be set to indicate certain events, and sleep/idle is not one of them.
However the nRESET pin is optional, and you can use the setPins() function in the LoRa library to change which pin it's connected to - and one option is to set it to -1 in which case the library ignores it (this must be run before .begin() is called) as it's only used during begin() to initially reset the LoRa module.
You could either tie nRESET HIGH (to 3.3V) to never reset it, or couple it with the reset signal of another peripheral so it gets reset at the same time - just be careful with your initialisation order in this case so you don't reset the module after configuring it...


How to reprogram Arduino if USB port is already in use? I'm developing a keyboard emulator using Digispark Pro (based on Arduino) which uses USB port as the keyboard interface. I haven't programmed it yet because I doubt how should I recognize the chip to Arduino IDE again using USB port after programming the board.

So my question is, how to reprogram Arduino if USB port is already recognized as keyboard HID?

https://digistump.com/wiki/digispark/tutorials/connectingpro
It is suggested that in order to upload using the Arduino IDE you must:

Add the repository http://digistump.com/package_digistump_index.json in Preferences > Additional Boards Manager URLs
Install Digistump from the boards manager.
select the DigiSpark in Tools > Boards.
Then this is perhaps the important bit "You do not need to plug in your Digispark Pro before invoking upload"   So hit upload before connecting the Digispark.
Then connect the Digispark when prompted by the Arduino IDE.


Serial data not parsed correctly The code I have works for the most part but when I send data via bluetooth received over software serial, too quickly, it is not parsed correctly.

I'm a bit stuck with what can be done to a void the incorrect formatting, since it works correctly if I send data slowly.

I could have a buffer to not send data more than once every set amount of time, but more responsiveness is preferred.

I am sending a string "center:255,0,255;"
it saves the command in a char array untill it sees the ":", then it saves the red in a  char array breaking on "," then same for the blue and green. when it  reaches the ";" it send the four arrays to print to a console. Later it the data will be used to light specific leds based on the command, but when I send data too quickly it gets parsed incorrectly, for example:

command: center
red:195
green:0
blue:255
command: center
red:208
green:0center:221
blue:0,255
command: center
red:246
green:0
blue:255

the 'green:0center:221' isnt correct, its either not seeing the "," or seeing the ";" too soon. Not sure how to avoid it.

#include <SoftwareSerial.h>
SoftwareSerial mySerial(6,7); // RX, TX

void setup() {
  Serial.begin(9600);
  mySerial.begin(57600); //required when using the hm-10 with an arduino nano
  mySerial.listen();
}

void loop() {
  while (mySerial.available () > 0) {
    processIncomingByte (mySerial.read ());
  }
}

const unsigned int MAX_INPUT = 50;

void processIncomingByte (const byte inByte) {
  static int parse_the_string = 0;
  static char command [MAX_INPUT];
  static char red [MAX_INPUT];
  static char green [MAX_INPUT];
  static char blue [MAX_INPUT];
  static unsigned int input_pos = 0;
  switch (parse_the_string) {
    case 0:
      switch (inByte) {
        case ':':
          command [input_pos] = 0;  // terminating null byte
          input_pos = 0;
          parse_the_string ++;
          break;
        default:
          if (input_pos < (MAX_INPUT - 1))
            command [input_pos++] = inByte;
          break;
      }
      break;
    case 1:
      switch (inByte) {
        case ',':   // end of text
          red [input_pos] = 0;  // terminating null byte
          input_pos = 0;
          parse_the_string ++;
          break;
       default:
          if (input_pos < (MAX_INPUT - 1))
            red [input_pos++] = inByte;
          break;
      }
      break;
    case 2:
      switch (inByte) {
        case ',':   // end of text
          green [input_pos] = 0;  // terminating null byte
          input_pos = 0;
          parse_the_string ++;
          break;
        default:
          if (input_pos < (MAX_INPUT - 1))
            green [input_pos++] = inByte;
          break;
      }
      break;
    case 3:
      switch (inByte) {
        case ';':   // end of text
          blue [input_pos] = 0;  // terminating null byte
          // terminator reached! process input_line here ...
          process_data (command, red, green, blue);
          input_pos = 0;
          parse_the_string = 0;
          break;
        case '\r':   // discard carriage return
          break;
        default:
          if (input_pos < (MAX_INPUT - 1))
            blue [input_pos++] = inByte;
          break;
      }  // end of switch
      break;
    default:
      break;
  }
}

void process_data (const char * command, const char * red, const char * green, const char * blue)
  {
  // for now just display it
  Serial.print ("command: ");
  Serial.println (command);
  Serial.print ("red:");
  Serial.println (red);
  Serial.print ("green:");
  Serial.println (green);
  Serial.print ("blue:");
  Serial.println (blue);
  }

Set higher baud rate for Serial and in Serial Monitor. It slows down the processing and the mySerial buffer overflows.


embedXcode: Link Error using an Arduino library (Servo.h) within a header file For various reasons, I am moving from the Arduino IDE to Xcode using the embedXcode plugin. The code in question compiles and uploads fine from the Arduino IDE, so I think the issue is related to library definitions in embedXcode. The board I am using is an Arduino Mega 2560 (actually it is a Freetronics EtherMega).

The error thrown is:

Command /Applications/Xcode.app/Contents/Developer/usr/bin/make failed with exit code 2

More specifically:

    5.3-LINK                    Builds/embeddedcomputing.elf

/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++ -o Builds/embeddedcomputing.elf Builds/main.cpp.o Builds/embeddedcomputing.a -Os -w -mmcu=atmega2560 -Wl,--gc-sections  -LBuilds -lm
Builds/main.cpp.o: In function `Robot::Robot()':
main.cpp:(.text._ZN5RobotC2Ev[Robot::Robot()]+0x5e): undefined reference to `Servo::Servo()'
Builds/main.cpp.o: In function `Robot::begin()':
main.cpp:(.text._ZN5Robot5beginEv[Robot::begin()]+0x5a): undefined reference to `Servo::attach(int)'
main.cpp:(.text._ZN5Robot5beginEv[Robot::begin()]+0x64): undefined reference to `Servo::write(int)'
main.cpp:(.text._ZN5Robot5beginEv[Robot::begin()]+0xea): undefined reference to `Servo::write(int)'
main.cpp:(.text._ZN5Robot5beginEv[Robot::begin()]+0x112): undefined reference to `Servo::write(int)'
main.cpp:(.text._ZN5Robot5beginEv[Robot::begin()]+0x132): undefined reference to `Servo::write(int)'
Builds/embeddedcomputing.a(HB25MotorControl.cpp.o): In function `HB25MotorControl::HB25MotorControl(unsigned char)':
HB25MotorControl.cpp:(.text._ZN16HB25MotorControlC2Eh+0x14): undefined reference to `Servo::Servo()'
Builds/embeddedcomputing.a(HB25MotorControl.cpp.o): In function `HB25MotorControl::begin()':
HB25MotorControl.cpp:(.text._ZN16HB25MotorControl5beginEv+0x42): undefined reference to `Servo::attach(int, int, int)'
HB25MotorControl.cpp:(.text._ZN16HB25MotorControl5beginEv+0x58): undefined reference to `Servo::writeMicroseconds(int)'
Builds/embeddedcomputing.a(HB25MotorControl.cpp.o): In function `HB25MotorControl::stop()':
HB25MotorControl.cpp:(.text._ZN16HB25MotorControl4stopEv+0x12): undefined reference to `Servo::writeMicroseconds(int)'
Builds/embeddedcomputing.a(HB25MotorControl.cpp.o): In function `HB25MotorControl::moveAtSpeed(int)':
HB25MotorControl.cpp:(.text._ZN16HB25MotorControl11moveAtSpeedEi+0x44): undefined reference to `Servo::writeMicroseconds(int)'
collect2: error: ld returned 1 exit status
make: *** [Builds/embeddedcomputing.elf] Error 1
Command /Applications/Xcode.app/Contents/Developer/usr/bin/make failed with exit code 2

Robot.h contains a robot class which defines a Servo (for a turret) and two HB-25 MotorControl objects (which control the drive motors). The HB25MotorControl is a custom library that I have written for the Parallax HB-25 Motor Controller. It also uses the Servo library.

To answer the obvious questions:

Yes I have #include <Servo.h> in my HB25MotorControl library. You
can see the library code by following the link above. It is also
included in the main sketch.
I have compiled, linked and uploaded other sketches which use Arduino and custom libraries in Xcode using the embedXcode plugin.
My embedXcode Makefile definitions include
    the Servo library and the HB25MotorControl library. See extract
    below.

APP_LIBS_LIST = Wire Servo SoftwareSerial

USER_LIBS_LIST = NewPing Time DS3232RTC HB25MotorControl

Any suggestions on how to fix this error and get my code to build in Xcode would be greatly appreciated.

I ended up contacting the developer of the embedXcode plugin. He was very helpful and provided the fix within a day. The cause of the issue is apparently the Arduino IDE has changed its library structure in the latest release.

The next version of embedXcode (release 4.1.4.) will include a fix for this, however if you can't wait until then you need to open ArduinoAVR_165.mk (located in the Makefiles group in Xcode) in your project and add the following line:

avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src/$(BUILD_CORE),$(APP_LIBS_LIST)))

After you add this line, the file should look like this:

# Two locations for Arduino libraries
#
APP_LIB_PATH = $(APPLICATION_PATH)/libraries
APP_LIB_PATH += $(APPLICATION_PATH)/hardware/arduino/$(BUILD_CORE)/libraries

avr165_20 = $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%,$(APP_LIBS_LIST)))
avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/utility,$(APP_LIBS_LIST)))
avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src,$(APP_LIBS_LIST)))
avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src/utility,$(APP_LIBS_LIST)))
avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src/$(BUILD_CORE),$(APP_LIBS_LIST)))
avr165_20 += $(foreach dir,$(APP_LIB_PATH),$(patsubst %,$(dir)/%/src/arch/$(BUILD_CORE),$(APP_LIBS_LIST)))

Note that each project has its own ArduinoAVR_165.mk file, so you will have to make this change in each project until you update to the new release.


Different questions regarding Arduino C++ library coding style I'm reading the two wire library in Arduino libraries and in the C++ source  code I found different methods which I don't know what they mean, in the following:

// Initialize Class Variables //////////////////////////////////////////////////

uint8_t TwoWire::rxBuffer[BUFFER_LENGTH];
uint8_t TwoWire::rxBufferIndex = 0;
uint8_t TwoWire::rxBufferLength = 0;

uint8_t TwoWire::txAddress = 0;
uint8_t TwoWire::txBuffer[BUFFER_LENGTH];
uint8_t TwoWire::txBufferIndex = 0;
uint8_t TwoWire::txBufferLength = 0;

uint8_t TwoWire::transmitting = 0;
void (*TwoWire::user_onRequest)(void);
void (*TwoWire::user_onReceive)(int);

// Public Methods //////////////////////////////////////////////////////////////
void TwoWire::begin(void)
{
  rxBufferIndex = 0;
  rxBufferLength = 0;

  txBufferIndex = 0;
  txBufferLength = 0;

  twi_init();
}

void TwoWire::begin(uint8_t address)
{
  twi_setAddress(address);
  twi_attachSlaveTxEvent(onRequestService);
  twi_attachSlaveRxEvent(onReceiveService);
  begin();
}

void TwoWire::begin(int address)
{
  begin((uint8_t)address);
}

My first question, regarding to class variables:

Why has the author connected the variables to the class with scope-resolution operator "::"?
I want to understand the last two lines of class variables, I know they are function pointers, but I want to know more details and benefits of function pointers?

My second question, regarding to public methods:

There are three versions of the "begin" function, can someone explain why?
Why is begin(); called inside the second function declaration?

Why they connect the variables to the class with scope-resolution operator "::"?

Those are static variables. They don't exist within an instantiated class instance since they are common to all class instances - so they have to be defined elsewhere, and for that you need the full "class path" for them to associate them with the class itself.

  I want to understand the last two lines of class variables, I know they are function pointers, but I want to know more details and benefits of function pointers?

Yes, they are function pointers. They are used to store the address of functions the user supplies at runtime. Without them it is very hard for the user to tell the class which of his own functions should be called for various events.

  There are three versions of the "begin" function, can someone explain why?

This is called function overloading. It allows you to have the same function but provide different combinations of parameters. In this case one with no functions (in master mode) and two with different numeric parameters (for slave mode) with those numeric parameters in different storage formats.

  Why begin(); is called inside the second function declaration?

It saves having to duplicate all the code from the other begin() function within that function. You call the function with a numeric parameter, it does a little bit of "extra" work, then it calls the "common" begin code from the other begin() function. Code duplication is generally a bad thing since any changes you make have to be made in multiple places. This keeps the common code in one location, and the most convenient place for that is the begin() function that takes no parameters.


USART RX Interrupt on an ARDUINO PRO MINI containing factory bootloader Is it possible to use RXC Interrupt vector with the factory programmed bootloader still existing in the arduino pro mini?

I've written a simple echo program using RXC interrupt vector, the program prints "READY" on startup but as soon the chip receives the first character it goes into a repetitive reset loop i.e. I keep receiving READY READY READY.. so on.

I've checked the program multiple times and I think its the bootloader, I think the bootloader has shifted the interrupt table to the boot section before executing the application. Is that so?

Thanks in advance.

Once the bootloader transfers control to the main code (sketch) it may as well not exist any more. It does not affect the way the sketch runs.

  I've written a simple echo program using RXC interrupt vector ...

Please post this code. For you to print "READY" you are (presumably) using the Serial port, in which case the HardwareSerial interrupt vectors are being used. I don't know how you managed to take over those vectors. Seeing your code might answer that.


lcd byte array display when reading RFID(MIFARE) information using Arduino mega and display in serial monitor it works fine. But, when printing on 2004LCD only one information(Value) displays correctly. The other information Item Name display a decimal number. Could someone help on this?
 void Price(){
      block = 4;
      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 4, &key, &(mfrc522.uid));
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("Authentication failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      status = mfrc522.MIFARE_Read(block, buffer1, &len);  // ***Note down buffer1 within the bracket
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("Reading failedl: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
             //Display price information...
      for (uint8_t i = 0; i < 16; i++)
      {
        if (buffer1[i] != 32) // if buffer1[i] not equal to 32
        {
          Serial.write(buffer1[i]);  //Price
         //lcd.write(buffer1[i]);
          Value = buffer1[i];
          }
       }
      Serial.print("/=");
      Serial.println(" ");
      sscanf(buffer1,"%d",&Value);
      lcd.setCursor(0,1);
      lcd.println(Value);

     }
    //==========================================================
    void Item(){ //----- Get & Display Item information
        block = 1;
     status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid));
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("Authentication failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      status = mfrc522.MIFARE_Read(block, buffer2, &len);
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("Reading failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      for (uint8_t i = 0; i < 16; i++) { //
         Serial.write(buffer2[i]);       // Display Item
         lcd.write(buffer2[i]);
         Item_Name=buffer2[i];
        }
        sscanf(buffer2,"%s",&Item_Name);
       //sprintf(buffer2,"%d",&Item_Name);
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print(Item_Name);// displays numbers instead of "Fresh Milk 1Lt
     }

Consider the following:
char buffer2[16];  // array of 16 chars
for (uint8_t i = 0; i < 16; i++) {
    do_something_with(buffer2[i]);  // handle one char at a time
}

Here we have an array of 16 cells, each having the char type (which I
assume is what you have). The loop goes through the array, handling one
cell a time. Within the loop, buffer2[i] represents the char being
currently handled.
Keep in mind that a char is just an 8-bit integer. It is somehow
implied that it is meant to represent a character, where 32 = ' '
(space), 33 = '!', 48 = '0', 65 = 'A' and so on (see ASCII).
The Arduino print() methods do assume a char (unlike an int) is
intended to be displayed as a character.
Now your actual loop:
int Item_Name;
for (uint8_t i = 0; i < 16; i++) {
    Serial.write(buffer2[i]);  // write the char on the serial port
    lcd.write(buffer2[i]);     // write the char on the LCD
    Item_Name=buffer2[i];      // store the char in a variable
}

This will print the contents of the buffer to both the serial port and
the LCD. You would have seen the expected message on the LCD if you did
not have lcd.clear() right after the loop.
sscanf(buffer2, "%s", &Item_Name);

This means “extract from buffer2 a sequence of contiguous
non-white-space characters, and store it in memory at the address of the
variable ItemName”. If the buffer contains “Fresh Milk 1Lt”, this will
write “Fresh” to that memory location. That is 6 bytes (5 letters and a
terminating NUL). Unfortunately, the compiler has only allocated 2 or
4 bytes of RAM for storing ItemName (depending on the Arduino model),
so this will write past the allocated storage, which is a type of bug
known as buffer overflow. Now your Arduino's memory is corrupted and
anything can happen.
sprintf(buffer2, "%d", &Item_Name);

This tries to find within byffer2 a textual representation of a
number, and store it into Item_Name. This is safe, but only makes
sense if the buffer contains a number, written as text, which is not the
case here.
lcd.print(Item_Name);

This is asking the LCD to print an integer (namely Item_Name). It will
convert the integer to decimal text and print the corresponding digits
on the LCD.
Let's assume for example that Item_Name contains the numeric value
32 (which is the ASCII representation of a space). lcd.print() will
convert that into a sequence of two characters: '3' and '2' (the
decimal representation of 32). It will then send those characters to the
LCD (ASCII values 51 and 50), and you will see the text “32”.
If you want to see the text contained within the buffer, the you can
either send the characters one by one (like you already did right before
lcd.clear()), or provide to lcd.print() a char* pointer with the
whole message:
lcd.print(buffer2);

This assumes that the buffer is terminated with a NUL character. If it
is not, then you can either use the char-at-a-time method, or change
your code in order to put a NUL terminator in the buffer.


cannot read from softwareserial I am able to use AT command from the Serial monitor however when I run the following code nothing is sent or received from the ESP8266. Can someone advise what could be the problem.

#include <SoftwareSerial.h>;

SoftwareSerial esp8266(0,1); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                            // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different
}

void loop()
{
 if(esp8266.available()) // check if the esp is sending a message
  {
    while(esp8266.available())
    {
      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      Serial.write(c);
    }
  }

  if(Serial.available())
  {
    // the following delay is required because otherwise the arduino will read the first letter of the command but not the rest
    // In other words without the delay if you use AT+RST, for example, the Arduino will read the letter A send it, then read the rest and send it
    // but we want to send everything at the same time.
    delay(1000);

    String command="";

    while(Serial.available()) // read the command character by character
    {
        // read one character
     command+=(char)Serial.read();
    }
    esp8266.println(command); // send the read character to the esp8266
  }
}

SoftwareSerial esp8266(0,1)

You can't use pins 0 and 1 for software serial since they are the hardware serial Serial than you use for communication with the PC.

Pick two other pins to use.


two 7HC595 and only 12 outputs im new to arduino and thinking to create a LED project.

im creating a LED project and i want to control 12 LED's. so i use two 7HC595 but problem i face is how can i only control 12 outputs ?

and i want to create multiple blink patterns with 12 LED, please be kind enough to provide blink patterns that i can modify and create different partners.

i have found many shift-out programs but i do not understand how to limit it to 12 outputs and create multiple blink patterns.

thanks

Do not worry about limiting it to 12 bits, send all 16 and use just the twelve you need.  You never know you may expand the project.  Whatever is on the unused bits is irrelevant. they do nothing.


nrfl2041, WIFI, bluetooth, xbee, zwave, other wireless communications Have a project using up to 200 sensors. communication method needs to be wireless. Sensors need to communicate data to the cloud or to a local storage device. Data is transmitted 6 to 24 times per day only. Data size is less than 1KB per sensor in most cases. Transmission distance is less than 150' in most cases. Transmitted data described here is digital, but might be analog if needed. Cost is a big issue. Power consumption is also a big issue but less important than cost. What method would you use nrfl2041, WIFI, bluetooth, xbee, zwave, or other wireless communications method? Love to hear your opinion.

Nrf24l01 with mesh or star setup is the best sollution for you. Other modules are expensive. Also bluetooth doesnt support over 7 nodes.  you can solder 8cm wire to nrf modules to get better signal and increse range. Alternatively you can use "nodemcu". Xbee-zigbee has hibernate function to increse battery life. You can apply enable-disable technique to improve the battery life but it is not preffered beacause of network performance. it is diffucult to assign addresses, setup network topology, and establish routing tablet for every hibernation period. You can choose cheaeper zigbee modules like microchips mrf24j40ma.


float precision in arduino I am reading a string which i have to convert into a float with a maximum of precision.I didn't want to use toFloat() function since it make a truncation so i made my own code.
My problem is that the final result is also approximated.
I need a precision of 4 digits after the float.I read the documentation about float in the arduino website.They say it should be maximum 7 digits of precision but i don't get it.When i test my code on the value of '23,459' ,all i get is 23,46.
Any suggestions?

void setup() {

 Serial.begin(9600);

}
int longu=0;
char data='2';
  String data2="23,459";
  float val=0;
  int posVir=0;
  int t=0;
  float postVir=0;
  float preVir=0;
  int lonPostVir=0;
  int lonPreVir=0;
  float posvir2=0;
  void loop()
{

   lonPostVir=(data2.substring(posVir+1)).length();
   lonPreVir=(data2.substring(0,posVir)).length();

   longu=data2.length();
   posVir=data2.indexOf(",");
   preVir=(data2.substring(0,posVir)).toFloat();
   postVir=(data2.substring(posVir+1)).toFloat();
   posvir2=postVir*pow(10,-lonPostVir);
   val=preVir+postVir*pow(10,-lonPostVir);

  Serial.println(val);

    }

The simplest way to get more decimal places to print is this:
Serial.println(val,NUMBER_OF_DECMIAL_PLACES);

This will print out any number of digits after the decimal place. Regular print without the number of digits specified will default to 2 decimal places. for example, here is some code and the result that gets printed:
float val = 23.459;
Serial.println(val);
Serial.println(val, 4);
Serial.println(val, 10);

23.46
23.4590
23.4589996337

You may notice that with 10 decimal places printed you can start to see how much the actual value of 23.459 needs to be approximated to fit within a floating point number. This is similar to how 1/3 can not be represented 100% accurately in a finite number of decimal digits; 459/1000 cannot be represented 100% accurately in a finite number of binary bits, so it is approximated.
Also, note that for non-floating point numbers the optional second argument to print and println is the base it should be printed in (dec, hex, oct, ...) and has nothing to do with precision.


How can I create multiple running threads? Is there a way I can have multiple parts of the program running together without doing multiple things in the same code block?

One thread waiting for an external device while also blinking a LED in another thread.

There is no multi-process, nor multi-threading, support on the Arduino. You can do something close to multiple threads with some software though.

You want to look at Protothreads:

  Protothreads are extremely lightweight stackless threads designed for
  severely memory constrained systems, such as small embedded systems or
  wireless sensor network nodes. Protothreads provide linear code
  execution for event-driven systems implemented in C. Protothreads can
  be used with or without an underlying operating system to provide
  blocking event-handlers. Protothreads provide sequential flow of
  control without complex state machines or full multi-threading.

Of course, there is an Arduino example here with example code. This SO question might be useful, too.

ArduinoThread is a good one too.


7805 powered Atmega328 Stops working when input of 7805 exceeds 7volts I am developing a circuit with atmega328, the MCU is powered by a LM7805.
The input of 7805 is given by a variable supply. Till the input of 7805 is 7volts, the output voltage is 4.9volts and current is around .75amps. Now if the input voltage of 7805 is increased, the current also increases and the MCU stops working(sometimes work with being reset after a few seconds), please help me out guys... i need to connect those circuits to my car battery, so it must work with 12volts.

I added capacitors and diodes as per Majenko mentioned. Now the situation is a) The circuit is working at 12V, b) With single C817 , output voltage of mcu is 3.5V, c)I used 56 ohms resistance, which is giving 1.2V to the input of C817, d) The Collector to Emitter resistance of C817 is 1520 ohms when turned on, this is creating a voltage drop of 3volts. e) This output is turning the led on, but being unable to switch the relay.

Circuit Upate

This the modified circuit, which solves the problem. But i have some questions, in the modified circuit if BC547 is used then its not working because the collector voltage which should be around 0.2 remains 1.8 volts, but replacing the BC547 with BC337 solves the problem(Collector voltage becomes around 0.3).

It looks like the reason for the MCU drawing high current is operating the LEDs in half a dozen optical isolators without current-limiting resistors.  The part number of your isolators apparently is PC817, for which the suggested LED current is 5 to 20 mA at about 1.2 to 1.4 forward volts.  But if you don't limit the current, they are likely to draw 50 to 100 mA each when turned on.  Add a series resistor, say 220 to 330 Ω, in series with each isolator.

At this point, it's possible you may have damaged your ATmega328 by overheating it, due to drawing too much current from its outputs.  You probably should run some tests with simple sketches to see if they all work ok.

Note, it probably would make sense to use a buck regulator rather than a linear regulator in the 12 V environment.  MP1584-based buck regulator boards (“Mini DC 4.5~28V to DC 3.3V MP1584 3A Step-down Converter Regulator Module”), about 2x2 cm, are about a dollar on ebay and handle 2 amps typically.


What is a faster alternative to parseInt()? I'm making an LED spectrum analyzer with an Arduino Due and my PC. The audio processing is done on the PC, and then sent to the Arduino. The exact data sent is a 'coordinate', or more specifically, a number representing a particular band, and another number representing the maximum amplitude of that band. There are 11 bands. Each coordinate has a x and a y value, separated by a comma, and then sent on a new line.

This is my code as of now:

void loop() {
  if (Serial.available()) {
    xCoord = Serial.parseInt();
    yCoord = Serial.parseInt();
    if (xCoord != 0) {
      int r, g, b;
      for (int i = 0; i < 8; i++) {
        int fromCoordToIndex = ((xCoord - 1) * 8) + i;
        //
        //do some calculations for the color
        //
        strip.setPixelColor(fromCoordToIndex, strip.Color(r, g, b));
        strip.show();
      }
    }
  }
}

The problem is parseInt seems to be very very slow (it's not the timeout issue, it's set to 1). From what I can see, it seems to be skipping some data, so every now and then a band gets missed out. The only way I can fix this is to insert a delay between each coordinate being sent. I found that 40 ms works ok, but remember there are 11 bands, so that means about half a second to refresh the whole board, which feels like a slide show...

I've tried inputting individual characters and then using toInt, I've tried parseInt obviously, I've tried native USB (it's a Due), and I've tried fiddling with baud rates. None seems to have had any effect.

The annoying thing about parseInt() is not its speed, it's the fact
that it relies on a timeout. If the timeout is too long, it slows you
down. If it's too short, it may induce errors.

A safer way to parse the sort of messages you are using is to buffer all
the incoming characters until you find a carriage return, then parse the
whole line. For example:

// Just echo the messages with a different separator.
void parse(char *buffer)
{
    char *s = strtok(buffer, ",");
    int x = atoi(s);
    s = strtok(NULL, ",");
    int y = atoi(s);
    Serial.print(x);
    Serial.print(':');
    Serial.println(y);
}

void loop()
{
    static char buffer[BUFFER_SZ];
    static size_t lg = 0;
    while (Serial.available()) {
        char c = Serial.read();
        if (c == '\r') {        // carriage return
            buffer[lg] = '\0';  // terminate the string
            parse(buffer);
            lg = 0;             // get ready for next message
        }
        else if (lg < BUFFER_SZ - 1) {
            buffer[lg++] = c;
        }
    }
}

Note that you should add some error checking when you call strtok().


use button to select variable i have a need to use 3 buttons a a simple option/variable selector at sketch start up ...

Pretty much at startup , script must wait for button press ( one of 3 ) , when button is pressed , use that buttons predefined string value as a variable for the loop script further down .. if wanting to change the "variable" then a reboot is required ..

i know how to digital read in the buttons , but not sure how to

1) wait for one of the buttons to be pressed to then jump to main loop
2) Associate a "string" variable to each button

thinking about it i suppose a If/Else loop will be required for the Input 'wait" and then just if the digital input (button) is pushed then continue .. am i correct ?

Ideas or better way to do it ?

Thx
Greg

When I am searching for something inside a loop, I find that the
simplest thing to do is to just break out of the loop once I found it.
This was frowned upon in the days when structured programming was a hot
thing, but as long as it makes things simpler, you should not be ashamed
to break:

const int button_pins[] = {2, 3, 4};
const char * const urls[] = {"foo.com", "bar.org", "baz.net"};
const char * url;  // the selected URL

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

    // Configure input pins.
    for (int i = 0; i < 3; i++)
        pinMode(button_pins[i], INPUT_PULLUP);

    // Find first button pressed.
    int i;  // button index
    for (i = 0; ; i = i==2 ? 0 : i+1) {
        if (digitalRead(button_pins[i]) == LOW)
            break;
    }

    // The button index selects the URL.
    url = urls[i];

    Serial.print("Selected URL: ");
    Serial.println(url);
}

void loop() {}

The for loop above is written as an endless loop (no end condition).
The expression i = i==2 ? 0 : i+1 means: “if i is 2, make it 0,
otherwise make it i+1”. In other words, we are endlessly looping i
over 0, 1 and 2.

Now, it may well happen that you actually do not care about which button
was pressed once you have selected the proper URL. In this case, you can
use the URL pointer as a “flag” that tells you when you can end the
loop:

// First button pressed selects the URL.
for (int i = 0; !url; i = i==2 ? 0 : i+1) {
    if (digitalRead(button_pins[i]) == LOW)
        url = urls[i];
}

Where !url means “the URL has not been found”. This works because the
C runtime initializes url to zero, which is interpreted as false in
boolean context.

Addendum: If you are likely to add new button/URL pairs, you can
make this easier by structuring the list as an array of structs:

const struct {
    int pin;          // pin number
    const char *url;  // associated URL
} buttons[] = {
    {2, "foo.com"},
    {3, "bar.org"},
    {4, "baz.net"}
    // etc. just add to this list as needed.
};
const size_t button_count = sizeof buttons / sizeof buttons[0];

Then the search becomes:

for (int i = 0; !url; i = i==button_count-1 ? 0 : i+1) {
    if (digitalRead(buttons[i].pin) == LOW)
        url = buttons[i].url;
}


Parse a large json response with ESP8266 I'm doing a project where my Arduino uses an external ESP8266 wifi module (with AT firmware) to send http requests and receive server response.

I'm trying to get an NBA scoreboard, and here's what my Arduino sends to ESP:

> AT+CIPSTART=0,"TCP","data.nba.net",80
0,CONNECT

OK

> AT+CIPSEND=0,103
SEND OK

> GET /data/10s/prod/v1/20190214/scoreboard.json HTTP/1.1
Host: data.nba.net
Connection: keep-alive

+IPD,0,1460:HTTP/1.1 200 OK..
.............................
...here comes the response...
.............................

Now the code works fine, and I'm able to get the json file needed. The problem is that the response is sometimes too long and the file gets truncated, thus the response is incomplete. The file itself is sometimes pretty large, but I only need a few numbers from it (current teams + current score). So my questions are:

I use readString() method (of SoftwareSerial object instance) to read the response. Is there a way to parse the response chunk by chunk without loading everything in my ESP memory?
Is there a way to limit the response?
Are there any alternatives to the method I'm using? Maybe parsing the website (nba.com or espn.com/nba) directly? If so, how can I do that?
Maybe there's a way to write a separate (free) online API to parse json, constraint the response and send the small version upon request?

PS. I tried doing the same without AT firmware, flashing the module with a code that used HTTPClient directly (with ESP8266WiFi.h and ESP8266HTTPClient.h libraries):

HTTPClient http;
http.begin(request);
if (http.GET() > 0) {
    response = http.getString();
}
http.end();

That didn't help much. I'm still running out of memory since I'm directly loading the response to memory with getString().

PPS. Just in case it matters, I'm using ATmega2560 and a small ESP-01 module (similar to this).

Ok, so I was able to do this. Here's the workaround.

Let's say the GET response is a flat string containing large .json file with all the commas and curly brackets. The idea is to read it byte-by-byte and instead fo storing it just find whatever key you need and extract its value.

We want to find the field containing, say, "97.5 FM" from http://data.nba.net/data/10s/prod/v1/20190223/scoreboard.json (that's at the very end), skip 3 bytes (which is just " | ") and then read and Serial.print 4 bytes (which is "1280")*. We would do something like this (of course make sure to connect to wifi and include <ESP8266HTTPClient.h>:

HTTPClient http;
http.begin("http://data.nba.net/data/10s/prod/v1/20190223/scoreboard.json");
int httpCode = http.GET();
if (httpCode == HTTP_CODE_OK)
  Serial.println(getValue(http, "97.5 FM", 3, 4));

where the getValue() function is defined as follows:

String getValue(HTTPClient &http, String key, int skip, int get) {
  bool found = false, look = false;
  int ind = 0;
  String ret_str = "";

  int len = http.getSize();
  char char_buff[1];
  WiFiClient * stream = http.getStreamPtr();
  while (http.connected() && (len > 0 || len == -1)) {
    size_t size = stream->available();
    if (size) {
      int c = stream->readBytes(char_buff, ((size > sizeof(char_buff)) ? sizeof(char_buff) : size));
      if (len > 0)
        len -= c;
      if (found) {
        if (skip == 0) {
          ret_str += char_buff[0];
          get --;
        } else
          skip --;
        if (get <= 0)
          break;
      }
      else if ((!look) && (char_buff[0] == key[0])) {
        look = true;
        ind = 1;
      } else if (look && (char_buff[0] == key[ind])) {
        ind ++;
        if (ind == key.length()) found = true;
      } else if (look && (char_buff[0] != key[ind])) {
        ind = 0;
        look = false;
      }
    }
  }
  return ret_str;
}

You can call this getValue() whatever many times you like, but the strings you're looking for need to be only after each other, because the response to GET is read byte-by-byte just once.

There is probably (i.e., most likely) a better way of doing this, but this approach works and it's pretty fast, so...

* This, of course, is just an example, and you can overload this getValue() function definition to, say, read until it gets a curly bracket or whatever.


Arduino Servo Free Rotation I have a project where I use 22 servos. I attach all 22 of the servos in the setup and in the loop, I use myservo.write() command to make a particular servo move to a particular position.

The problem here is that, all the other servos become stiff at this point of time, even though I am not writing any value to those servos. By stiff I mean that the servo is holding at a particular random value. Which for most of the 22 servos is at or near 90°.

My question is how can I make a particular servo move, while allowing all the other servos to freely rotate. I think that when I attach a servo the program prevents the free rotation of the servo.

I was wondering if the signal to one of the servos is leaking to other servos because of an issue with wiring, but this is not the case. The other servos become stiff only when I attach them to the pins which have been "attached" as a servo in the program.

When you attach a servo the Arduino starts generating the PWM waveform for its currently selected angle. When you write to the servo you just change the current angle and the waveform changes to match. That waveform is constantly being generated from the moment the servo is attached, and will always be generated.  That is how servos work.  They are not really designed to be back-driven by the load turning the cogs - it is the role of the servo to do the driving, not to be driven.

Depending on the servo you might actually damage the mechanics by driving it backwards like that.

The only way you can stop the servo from being actively driven is to detach the pin from the servo system so that it doesn't think there is a servo there any more.


ERROR: Timed out waiting for Arduino 101 - anything I can do? I just received an Arduino 101 so I did the following in a wave of excitement...

Connected the USB cable between it and my Macbook Pro
Started the Arduino IDE version 1.6.7
Wrote a little bit of code
Selected Tools | Boards | Boards Manager... and installed the Intel Curie Boards as per Getting Started
Selected Tools | Board: "Arduino 101"
Selected Tools | port: "/dev/cu.usbmodemFA141 (Arduino 101)"
Selected Sketch | Upload

I was expecting something amazing, but I got the error:

Starting upload script
Payload: /var/folders/jr/5rmqcrqj58103d4p1f6_3sjr0000gn/T/build7c6ce067b9e8a57f9917c651ec494989.tmp/orientation.ino.bin
Waiting for device...
ERROR: Timed out waiting for Arduino 101.

Is there anything I can do to debug this or did I miss a step perhaps?

(I tried the good ol' turn it off and on again, including shutting the IDE down).

Press the reset button next to the USB port. (either one, the master reset is between the DC jack and USB ).

This will cause the Arduino 101 to reboot and enter DFU mode for 5 seconds if it is connected on USB. The download will proceed when the Curie enters DFU.

The IDE uses a baud-rate signal over USB. It is a virtual serial port, so baud rate doesn't matter. But when the host side (Arduino IDE) switches the baud rate to 1200, the board will reboot and enter DFU mode for download. If it gets stuck for some reason and misses the message to reboot, you can just hit the reset button and accomplish the same thing.


Arduino Mega 2560 bootloader delay I need to make my program run immediately on a reset or power up. However, the bootloader delays program startup by around 2.5 seconds. How can I get over this? Is there a way to turn off the bootloader wait period?

Yes.  You remove the bootloader completely and program the Arduino using a hardware programmer.

If you could "turn off" the wait period you would never be able to get into the bootloader to program the board, so the bootloader would be completely useless.  So either way you would then need a hardware programmer to do anything constructive with the board.

A hardware programmer could be another Arduino, or a real hardware programming adapter.


Difficult between atmega328 & atmega2560 when coding & compiling in a pure c I have an arduino uno with atmega328p controller.

I found the code to deal with some specific uart protocol, named mdb: https://github.com/Bouni/MateDealer/tree/master/arduino

But it's compiled just for atmega2560 controller: https://github.com/Bouni/MateDealer/blob/master/arduino/makefile#L42

If I replace it by atmega328p or atmega328, I get the error:

asiniy@misha:~/projects/MateDealer/arduino$ make all

-------- begin --------
avr-gcc (GCC) 4.8.2
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Compiling: main.c
avr-gcc -c -mmcu=atmega328 -I. -gdwarf-2   -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhlns=main.lst  -std=gnu99 -DF_OSC=16000000 -MD -MP -MF .dep/main.o.d main.c -o main.o

Compiling: usart.c
avr-gcc -c -mmcu=atmega328 -I. -gdwarf-2   -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhlns=usart.lst  -std=gnu99 -DF_OSC=16000000 -MD -MP -MF .dep/usart.o.d usart.c -o usart.o
usart.c:25:40: error: ‘UBRR1H’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                        ^
usart.c:25:49: error: ‘UBRR1L’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                                 ^
usart.c:25:58: error: ‘UCSR1B’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                                          ^
usart.c:25:67: error: ‘UCSR1C’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                                                   ^
In file included from usart.c:14:0:
usart.c: In function ‘USART0_RX_vect’:
usart.c:185:5: warning: ‘USART0_RX_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART0_RX_vect){
     ^
usart.c: In function ‘USART1_RX_vect’:
usart.c:197:5: warning: ‘USART1_RX_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART1_RX_vect){
     ^
usart.c:203:12: error: ‘UDR1’ undeclared (first use in this function)
     data = UDR1;
            ^
usart.c:203:12: note: each undeclared identifier is reported only once for each function it appears in
In file included from usart.c:14:0:
usart.c: In function ‘USART0_UDRE_vect’:
usart.c:233:5: warning: ‘USART0_UDRE_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART0_UDRE_vect){
     ^
usart.c: In function ‘USART1_UDRE_vect’:
usart.c:253:5: warning: ‘USART1_UDRE_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART1_UDRE_vect){
     ^
usart.c:261:31: error: ‘TXB81’ undeclared (first use in this function)
                 UCSR1B |= (1<<TXB81);
                               ^
usart.c:266:9: error: ‘UDR1’ undeclared (first use in this function)
         UDR1 = data;
         ^
usart.c:269:20: error: ‘UDRIE1’ undeclared (first use in this function)
     UCSR1B &= ~(1<<UDRIE1);
                    ^
make: *** [usart.o] Error 1

I've tried to play with compilers (default is gnu99) and so on, but with no success. Why I have this trouble? How can I compile this code for upload it to arduino?

I'm the author of the MateDealer project and I never had the intention to port it to other boards than the Arduino Mega2560!

Ignacio Vazquez-Abrams is absolutely right, the Arduino Mega2560 is the only board with more than 1 serial port (Yes there is the Due and the Leonardo, but those would require major changes to the code).

The fastest way to get the code running is by using a Mega2560, but be warned, the code might be bugy as hell ;-)


How to wire up 4-digit 7-segment display? I have an Arduino Mega and the CL5642BH, a 4-digit 7-segment display. I found very helpful code here, but I don't understand how to wire it up on the breadboard.

The display has 12 pins: 6 on the top and 6 on the bottom. First I guess I need to find out which one is GND.

Then (see the link) there is this code:

int digit1 = 11; //PWM Display pin 1
int digit2 = 10; //PWM Display pin 2
int digit3 = 9; //PWM Display pin 6
int digit4 = 6; //PWM Display pin 8

int segA = A1; //Display pin 14
int segB = 3; //Display pin 16
int segC = 4; //Display pin 13
int segD = 5; //Display pin 3
int segE = A0; //Display pin 5
int segF = 7; //Display pin 11
int segG = 8; //Display pin 15

It's 11 pins, that's the correct amount so far. But how do I wire it up? The pins on the display are in no way labeled.

Note: I'm a software developer, but as far as electronics go, I'm still a beginner.

The first thing you do is ask Google for a datasheet.  It tells you: http://www.robotshop.com/media/files/pdf/datasheet-com-09483.pdf

Then you can read the datasheet and find the pin diagram:

That tells you that it is a Common Anode LED display - which means that for each digit all the Anodes (positive pins) of the LEDs are wired together.

Further, all the cathode (negative) pins of the LEDs for the same segments across the digits are connected (that is the cathode for segment A on digit 1 is connected to the cathode for segment A on digit 2, digit 3 and digit 4, etc).

From that you can then infer that you need to provide current for each digit in turn through its common anode pin, and sink current from the segments you want to have lit for the digit that is currently having its current sourced.

The diagram also shows you which pin on the display is for what function - the common anodes are pins 9, 10, 12 and 13, with pin 11 the common anode for the extra dots.

The datasheet also tells you which pin is pin 1 - in this case the one in the bottom left when you have the display facing you and the numbers the right way up.  The pins count anti-clockwise from there, so 2 is to its right and 13 is above it.

By the sounds of it though you may not have the same display as in that datasheet.  If your display lacks the extra dots then it may not have the LEDs on pin 11, and pin 12-13 may be moved down one, so you have 4 commons on 9, 10, 11 and 12 with no pin 13.

So the four digit select pins in your program are wired to pins 9, 10, 12 and 13, and the segment select pins connect to pins 1, 2, 3, 4, 5, 6, and 7.  Don't forget the resistors on all the segment pins to limit the LED current or you will damage the Arduino.

You can do some manual testing of the display by using two wires and a resistor (say 1KΩ).  Connect the resistor to +5V, and one wire to the other end of the resistor.  The other wire you connect to ground.

You then take the loose ends of the wires and try probing pins.  Start with the 5V wire touching pin 9 and connect the other one in turn to pins 1-8 to see if the first digit's segments light up.  Repeat with the 5V wire on pins 10-12.

Edit:

If this (http://mklec.com/displays/7-segment-4-digit-12-pin-common-anode-display) is indeed the same display as yours you can ignore the numbers I mention above and work from the pin numbers on that page.  The same principle applies though, just the pin numberings are different.


Wiring parallel TFT with ESP32 I have this Parallel LCD TFT. I want to connect it with an ESP32 (NodeMCU). I am using the TFT_eSPI library.
In the TFT_eSPI documentation, it says that the connection should be as following:

// The ESP32 and TFT the pins used for testing are:
//#define TFT_CS   33  // Chip select control pin (library pulls permanently low
//#define TFT_DC   15  // Data Command control pin - use a pin in the range 0-31
//#define TFT_RST  32  // Reset pin, toggles on startup

//#define TFT_WR    4  // Write strobe control pin - use a pin in the range 0-31
//#define TFT_RD    2  // Read strobe control pin  - use a pin in the range 0-31
//#define TFT_D0   12  // Must use pins in the range 0-31 for the data bus
//#define TFT_D1   13  // so a single register write sets/clears all bits.
//#define TFT_D2   26  // Pins can be randomly assigned, this does not affect
//#define TFT_D3   25  // TFT screen update performance.
//#define TFT_D4   17
//#define TFT_D5   16
//#define TFT_D6   27
//#define TFT_D7   14

P.S. My tft does not have DC PIN. So, I wired nothing to GPIO15

After I wired the TFT, the ESP32 stop responding to flash process. and obviously, it did not run anything(even if I flash it without the screen and then wiring it again)

My question is:

What is the mistake did I do? How can I link this parallel LCD with ESP32

Sorry for the Late reply, I had the same issue.
You cant have anything connected to pin 15 or 2 during flash


How fast can I read Arduino port D? I'm trying to see how fast I can read an Arduino IO port.  It's being toggled with an random speed /white square wave and I want to see which is faster, the Arduino or the signal.  The pin on port D is driven by an open collector comparator (LM311).

So I have this code

buffer[0] = PORTD;
buffer[1] = PORTD;
buffer[2] = PORTD;
buffer[3] = PORTD;
buff...

...fer[28] = PORTD;
buffer[29] = PORTD;

that I can read the port in burst mode.  This code is as fast as I can write I think.  I've unrolled a possible loop here.  buffer[] is a local variable as that seems faster.  I'm not an assembly expert so I can't really browse the assembly instructions.

I've added a 500 Ohm pullup resistor to the input pin that I'm interested in.  A lower value seems to give more randomly distributed values that a 10k resistor.

I tried timing buffer[0] ... buffer[29] readings and that returns 4 microseconds with interrupts off.  I hope that micros() doesn't need interrupts to function!  That would equate to 7.5 million readings /sec.  That's about 2 clock cycles per instruction on my 16 MHz board.  Can this be right?

How fast can this code run?

Your timing seems reasonable.

At a rough guess, without actually compiling it, your code will turn into something along the lines of:

IN R24,PORTD  ;First read   - temp = PORTD     - 1 cycle
ST X+, R24    ;First store  - buffer[0] = temp - 2 cycle
IN R24,PORTD  ;Second read  - temp = PORTD     - 1 cycle
ST X+, R24    ;Second store - buffer[1] = temp - 2 cycle
...

This is indeed the fastest way of reading the port if you want to keep the data. Basically it will do an IO read from PORTD using the IN instruction which takes 1 clock cycle. Then it will perform a store to SRAM using the STS instruction which takes another 2 clock cycles. The store instruction can also post increment the pointer it is using (stored in the R28/R29 X-register pair in my example) for free which saves you time.

So basically that should do 3 clock cycles for every read - one to do the read, and one to do the store, or >5 million reads per second from a 16MHz clock.

There will additionally be a couple of cycles at the beginning to set X-register to point to the buffer. If the buffer is a constant pointer - i.e. the buffer has a fixed address, it will only take two instruction cycles at the beginning to load the address. If it is a non-constant address, it will take up to four as it has to load the address from the SRAM.


How to control speed of 28BYJ-48 stepper motor without using library? Iam using 28byj-48 stepper motor and I want to know how to control its speed without using any library. I got to know that we need to add delays in between steps but I don't know how much delay I need to add and how delay effects the rpm. It is very much helpful if anyone suggest me how to do this.

A stepper motor always needs a driver. As the ULN2003 (or similar) driver is normally shipped together with the 28byj-48 motor, I will assume, that you have this driver.
The ULN2003 has 6 pins:

Vcc and ground need to be connected to your power source. Note, that it is risky to connect Vcc to the 5V pin of the Arduino. While that might work, when there is no load on the motor, a loaded stepper motor can draw rather high currents. Letting these current run through the Arduino might fry the voltage regulator or the power switching diode. High currents should always flow past the Arduino, not through it.

The other 4 pins (which are marked as IN1 to IN4 on my ULN2003 driver board) are for controlling the phases. You need to connect these 4 pins to 4 individual digital outputs on your Arduino. As these are the phases of the stepper motor, you need to activate them in the correct order. You have this pattern
  1000
  0100
  0010
  0001

for full steps, and this pattern
  1000
  1100
  0100
  0110
  0010
  0011
  0001
  1001

for half steps. Each digit of each number represents the status of the corresponding phase; 1 means activated/HIGH, 0 means deactivated/LOW. To move the stepper motor forward, you move in the list of phases down. To move backwards, you move up in the list.

When using a stepper motor, the speed is determined by the number of steps per time interval. Let's assume, we want to use delay(), which is really easy, though not recommended (see explanation below), we can do steps and delay() inbetween:
void loop(){
    step();
    delay(10);
}

This code would do a step and then delay for 10ms. Thus we have about 1 step every 10ms. With 64*64=4096 steps per revolution (the motor itself seems to have 64 steps; additionally there is a gear with ratio 64 mounted on it; this might be different for you) we get a full revolution every 4.096s. When you use half the delay(), the speed will be double: with 5ms delay we get a full rotation every 2.048s. So you can use the delay() to set the speed of the motor.
Now we need the step() function, that I used above. There are multiple ways of writing this in code. I would propose to put the pins and phases into arrays and iterate through them with a static variable, which holds the current position in our phase pattern. Something like this:
//in global scope defining the pins for the phases
int stepper_pins[4] = {2, 3, 4, 5};

void step(bool forward){
    const uint8_t phase_pattern[][4] = {
        {1,0,0,0},
        {0,1,0,0},
        ...
    };
    static uint8_t current_step = 0;
    if(forward){
        current_step = (current_step + 1) % 4;
    } else {
        current_step = (current_step - 1) % 4;
    }
    for(uint8_t i=0;i<4;i++){
        digitalWrite(stepper_pins[i], phase_pattern[current_step][i]);
    }
}

We hold the phase pattern in a 2-dimensional array. The variable current_step is declared static, so it will keeps its value between the executions of the function. Then - depending on the parameter forward - we increment or decrement the current step and take that value modulo 4 (the number of phase patterns). That ensures, that current_step stays in the index range of our phase pattern array and will wrap around from the end of the pattern to the start and vice versa. After that, we loop through the 4 stepper pins and set them according to the current element in the phase_pattern array. You can easily adept that code for half steps.
Note, that this code is totally untested. Also this can be reached with way less code (at least for full steps), but I think this code is better understandable.
Now: Why not using delay()? This function will block the execution of other code. In that time the Arduino is just fiddling thumbs. In general that is considered bad practice. It is good, when you only need that one functionality and no responsiveness. But lets assume, you want to add a button, so that the motor reacts to your button presses. Long delay() calls will impact the responsiveness of your code. So instead you could use a non-blocking coding style. In the Arduino world this is easily done with the millis() function, which returns the number of milliseconds since startup and thus acts like a clock. Refer to the BlinkWithoutDelay example, that comes with the Arduino IDE, and to the many tutorials on the web, that you can find with search terms like "Arduino millis tutorial" or something like that.

EDIT:

how your code controlling the motor speed?

The delay() call is determining the motor speed. If you want to change the speed, you need to change the value of the delay. You didn't mention any input device, so I just leave the speed constant. But of course you can define a variable for the delay and change that delay based on some input device. How exactly that is done depends on your requirements, mainly what type of input you want to use.

if we didn't specify any delays in between steps, will it spin at its max rpm?

When you don't use any delay, then most likely your code will run too fast for the motor. The driver will set the motor phases very very fast. So fast, that the motor cannot follow that (because it has a specific inertia). (Much like the wheels of your car can loose the grip on the street and spin without moving the car, the stator of the motor can loose the magnetic grip on the rotor, which leads to further rotating phases, but a rotor, that is standing still) So you reach the maximum speed before that and it depends on the motor, the driver, how much load is on the motors and how much current your power source can give you (I once tried to provide 3 of these motors with a 1A power supply, but they moved very weak, until I upgraded to a bigger power supply, that can provide about 5A, I think). You need to test yourself, how fast you can drive your motors. So try to lower the delays step by step, until the motor cannot move in your setup anymore. Then you have the minimum delay, and the maximum speed.
Note: The delay() function won't be accurate for very low delays in the single digit milliseconds. In that case you might wanna use delayMicroseconds(), which is more accurate in that range and also can get in you in the microsecond range.


What is difference between analog and digital input and output, and when should i use anlog or digital (input or output)? How should i determine whether to use input as analog or digital and same for output too?

You will use digital pin modes when dealing with signals that are either "on" or "off", such as an LED, a switch, or another digital IC.

Analog inputs are used when you want to read the voltage potential of something. This is typically used to read analog sensors. Analog outputs are not really analog at all on the Arduino. Instead, the Arduino uses something called PWM to create a pseudo-analog signal.

You can read more about analog and digital here:
https://learn.sparkfun.com/tutorials/analog-vs-digital


How precise can I get Arduino using rotary encoders? Stepper motors are often pricey for a large motor. However, with a powerful, standard DC motor and a rotary encoder, you can "simulate" a stepper motor. How accurate are rotary encoders with Arduino just with a basic loop and not much other code? Is it going to "miss a pulse" and not record enough rotation often? How can I handle this with much more code? Is there a better way to do this? Would interrupts help? Is there some sort of circuit that would help with this problem?

Note: It will probably not exceed 4 rotations a second... (That may be a lot but if you're doing a lead screw type mechanism that would only be 24 inches a minute if there is 10 rotations per inch of linear motion.)

Interrupts are what you would use in this situation.

The rates that you have mentioned are slow enough where you probably would be able to count it inside of a loop, however this is not recommended, as a typical loop will take many clock cycles to complete, and depending on the number of instuctiuons per loop, you may miss some counts.

Interrupts are made for this purpose, as they can be triggered at any time, regardless of the state of the loop.

There is a function named attachInterrupt() which will take three arguments.

Interrupt Pin
Interrupt Service Routine
Mode

Below is an example for counting an interrupt

volatile int myCounter = 0;

void setup(){
    attachInterrupt(0, count, RISING);
}

void count(){
    myCounter++;
}

The Modes are as follows:

  LOW, CHANGE, RISING, FALLING

More information about using interrupts can be found here.

Depending on the encoder you use, you will need to tailor the code your needs, and do some more calculations to determine your position, but this should be a good starting point.

Edit
Here is some example code from Arduino Sandbox for using a rotary encoder.


Proxy and Authentication in Arduino Uno I am using the Ethernet Shield on top of the Arduino Uno. I want to use this setup to access  webpages. But I am unable to access because the ethernet connection is present in a University which requires a proxy server with authentication. I am unsure of what extra code to include so as to get past the proxy which requires authentication.
Can anyone help in solving this problem?

Any semi-reputable authentication mechanism would be performed over HTTPS, which is an encrypted connection - this would require an SSL library to be installed for use along with the normal Ethernet and HTTP libraries, and I don't believe the arduino really has the processing capability to make connections like this feasible.
Unfortunately this is one of those cases where a more sophisticated device may be more appropriate.... (like a Beaglebone Black, or a Raspberry Pi.)

It is possible that you could add headers into the HTTP connection packet to either bypass proxy authentication, or include a cookie that has already undergone authentication and is cached by the proxy. How you do this is almost entirely down to how your proxy works. You may also find this doesn't work unless you spoof the MAC address of your device to match that of the machine used to fulfill the authentication.

It is entirely possible to set up a system to share the internet connection (act as a router) between two adapters - so you end up making connection requests to webpages, but the authenticated proxy only sees requests coming from your system (this is kind of how mobile phone tethering works, when you access the internet on a laptop or tablet through your smartphone's internet connection).

If the proxy supports unencrypted authentication, it may be possible to pass through username/password details in plaintext (or Base64 encoded) in Basic access authentication, which is what HTTP (and HTTPS) often uses - but this is unsafe on HTTP and is VERY unsafe when any part of the connection is publicly transmitted - like when using wifi, for example. (Doesn't matter if the wifi is encrypted - as on a university network, everyone who can connect to the wifi can see your wifi traffic (typically).)

If you're going to be using your own personal university login credentials to do this, make sure you always use ethernet to do it, not wifi, and if possible, obtain a second username/password explicitly for connecting this way - you don't want to have to hard-code your own personal username and password into source code that you have to give to anyone.

Here's a few links to get you started:

HTTP Spec: Proxy-Authorization and Authorization headers
How to use authentication in an HTTP Proxy?
Wikipedia: X-Forwarded-For


Driving multiple LED arrays with shift registers The project I'm building requires multiple LED arrays. I'm going to wire these LEDs in parallel and then connect the arrays to individual pins on a shift register. In addition to the LEDs running in parallel I've connected resistors in series to each LED. I've been prototyping this on a couple of breadboards and I've noticed my parallel LEDs are much more dim then my LEDs I have in series. The resistors I'm using are around 550 OHMs and I'm powering the registers through my arduino uno. I think this may be part of the reason why they're so dim, as the arduino is only providing 5V. My question is, can I/should I have my registers connected to my arduino via the data connections and power them using an external source? Will this provide me with brighter LEDs? I don't want to dump the resistors, and I have around 21 arrays, if it matters, each with a varying number of LEDs

You haven't provided enough information to allow definitive answers to your questions, but you can apply LED resistor calculators and formulas to determine how much current is available to drive LEDs of various voltages.

Here is an example:  Suppose you hook up a red LED that drops about 1.6 V when it's on and operating at a current of 5 to 25 mA.  Suppose the LED is in series with a 550 Ω resistor, between a 5 V source and ground.  Current will be about (5-1.6)/550 A ≈ 0.0062 A = 6.2 mA.

If you wished to limit current through Arduino Uno pins to safe-area amounts like 25 mA, you could drive at most 4 such LEDs per output pin.  If you decrease the resistor to get more current, the number of LEDs allowed per pin decreases too.

Because pin voltage drops slightly as the pin drives more current, LED brightnesses will also decrease slightly as more LEDs are attached to a pin, so putting different numbers of LEDs on different pins is likely to make light levels uneven.

Limits on output currents from 74HC595 shift register pins are similar to those on Arduino Uno pins; eg 35 mA absolute max ratings for the Qn pins.

Rather than driving LEDs directly from Uno pins or '595 pins, you can use transistor driver stages.  Most transistor drivers will allow higher voltages (ie more LEDs in series, rather than in parallel) and higher currents.  Also consider using LED driver chips; many of them contain PWM circuitry for brightness control and registers for storing drive levels.