74HC595 to 5v pin shuts down uno I'm new to using the SN74HC595 shift register, and trying to follow this tutorial: https://www.arduino.cc/en/tutorial/ShiftOut based on this configuration:

When my arduino Uno R3 is plugged in by USB to my Windows-7 x64 PC, it works (in general etc.), but right when I attach pin 16 or pin 10 of the 74HC595  to the 5V pin on the Uno, as it says to do, the entire arduino shuts off and the computer no longer recognizes it, until I disconnect the jumper wire from pin 16 or 13, from the 5v pin on the Uno, then it starts up again
Also just tested, and the same thing happens when I try to connect any of the 74HC595  pins to the 5v Uno pin (after pin 8 of the 74HC595  is connected to the Uno's GND), the whole Uno shuts off and disconnects from the computer
Am I missing something here?

when I attach pin 16 or pin 10 of the 74HC595 to the 5V pin on the Uno ... the entire arduino shuts off

This sort of thing usually happens to me when I have made a mistake in the wiring.
This is easy to do as the 595 needs a lot of connections in a small space and it is easy to make a mistake.
In your case it seems you have a wiring mistake that is pulling Vcc low and the ATmega328 IC etc can't run.

I would

Re-check the orientation of the 595
Re-check each wire paying particular attention to the ground wires, especially the one that pulls 595 OE to ground (it's pin 13 on the 595).
If necessary, pull everything off the breadboard and start again with things in a completely different position (turn the IC's round etc) to make me re-think everything.

For fun, I set this up on a Uno clone. I made some mistakes in the wires linking the 595 to the Uno but careful inspection found the problem. I found it easy to mix up the pin-number on the 595 with that on the Uno. Using the same wire colours mentioned in the guide may help.
Here's it working


LCD showing weird characters when using two 1-wire temperature sensors I have a sketch to display a temperature obtained from 1-wire DS18B20 sensors. The sketch works fine, however when I connect two sensors to my board, the text on the LCD displays gets corrupted (### and other symbols shown instead of a temperature).

I have tried plugging each of the two DS18B20 sensors individually and it works with both of them, the problem shows only when I use both at the same time. I am connecting them both with black to ground, red to 5V and white to Dx and to 5V via a 4.7 kOhm pull-up resistor.

I have little idea how to check what is wrong - is it some kind of interference, insufficient voltage, or a SW problem?

After some more searching I have found Arduino forum topic LCD text corrupts after Arduino runs for length of time. I have followed this advice:

  In particular, try running the LCD ground wire directly to a ground pin on the Arduino (not to the breadboard) and keep it short.

This seemed to solve the issue, therefore it was likely some kind of interference on the ground wiring. (Before this, the ground to the LCD went trought the breadboard power bus).


Sending Integer > 1 Byte from Android to Arduino over Serial I´m using

public abstract void write(int b) throws IOException;

from class OutputStream on Android Studio to sent Integer (degrees from 0 to 360) to the Serial Port of my Arduino over HC06 Bluetooth module.

Degrees from 0 to 256 are read well by using

 int angle = Serial.read();

Values over 256 (1 Byte) are received as 0 are something weird.

I tried using

 Serial.parseInt();

as it should return an long int but all I get is one digit mostly 0.

I also tried using

Serial.readBytes(threeDigitsInt, 3);
angle = (threeDigitsInt[0] * 100) + (threeDigitsInt[1] * 10) + threeDigitsInt[2];

but I cannot tell what ends up in the array. Definitly not the correct single digit. I tried char[] and byte[] but I´m not able to reconstruct my send Integer value.

Summary: I want to send 360 as Integer from Android and have it as Integer on Arduino.

Appreciate your help!

First off, you are only sending one byte from Android:

  public abstract void write (int b)

  Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.

OutputStream.write(byte) can never write more than one byte.

Also it's clear you have no clue about what format the data is sent in if you are trying to then read 3 bytes and use Binary Coded Decimal to reconstruct it.

Instead I suggest you work in a purely ASCII format. Forget bytes. Bytes are not what you want, unless you feel like spending some extra time defining, and then implementing, your own protocol.

Start by formatting your data into an ASCII printable string.  If Android Java is anything like normal Java I'd start by turning your integer into a string with proper line endings.  Something like:

String val = String.format("%d\n", angle);

Then get the bytes that represent that formatted string:

byte[] valBytes = val.getBytes();

Now you have a valid byte array containing your textual representation of the data that you can send with OutputStream.write(byte[]).

Now your task is to read that data on the Arduino.  That means reading each byte that arrives in turn storing it away in some form until you receive the \n line ending.  At that point you can take each byte as a string and convert them into an integer again.

It's possible to do that on the fly:

static int angle = 0;

if (Serial.available()) {
    char c = Serial.read();
    if (c == '\n') {
        Serial.print("I got: ");
        Serial.println(angle);
        angle = 0;
    } else if ((c >= '0') && (c <= '9')) {
        angle *= 10;
        angle += (c - '0');
    }
}

Basically, have a variable that stores the incoming angle. For each character that arrives on the serial port - if it's a line ending \n then do whatever with the angle value. If it's a character between 0 and 9 then multiply your angle by 10 (decimal shift left), convert your character to the equivalent integer by subtracting character '0', and add it to your angle.


Why are Arduino clones cheap? You can buy Arduino Nano v3 clones from Alibaba at the cost of roughly $2-$3.

I have calculated the cost for fabricating and all the parts in the BOM for Arduino Nano V3, and it ended up costing around $10 to $12 (depending on where you fabricate the board, buy the components and purchasing volume - assuming less than 100 units).

However, how are Chinese clone manufacturers able to slash the price so much it's only ~1/10 of the BOM cost.

Could it purely be due to economy of scale, lower fixed costs (cheap labor), low quality parts (How do you define low quality parts)? Or are there other factors at play as well?

All the factors mentioned in the question apply to make the cost so low.  However, with an exception or two as noted in the next paragraph, “low quality parts” is not much of a factor, as explained in two paragraphs after that.

Possible low quality parts include the USB mini-B socket, crystals or resonators, and the reset switch.  The socket and switch contain metal shapes that can be well made or badly (and more cheaply) made.  Those badly made will function but may have shorter lives and higher failure rates.  For example, the USB cable fit may be loose, or the switch may fall apart.  Crystal or resonator accuracy and stability can be poor while still allowing a Nano clone to appear to function ok.

However, SMT (surface mount technology) or SMD (surface mount device) parts on the board cannot be made significantly more cheaply than can good parts.  SMD LEDs, resistors, diodes, voltage regulators, and capacitors come off of automated assembly lines with little or no manual intervention.  See, eg, ceramic capacitor manufacturing at wikipedia.  Parts are automatically packaged into sealed reels of parts suitable for use on an automatic pick-and-place machine that populates PCBs.  In short, the dozen 0603-size SMD LEDs, resistors, and caps, and the nine other passive or small-scale-integration SMD parts on the board will cost about the same coming off a bad manufacturing line as from a good line, so there is little profit to be made producing bad parts.  The 20-odd passive parts probably cost a couple of cents, at manufacturing scale.

Active SMD parts like voltage regulators, the ATmega328P, and the 32U4 or CH340, likewise come off automated manufacturing lines.  As these parts are more expensive, there is more economic incentive for cheating, and from time to time fake parts get sold and used.  In the past (and perhaps still) there have been manufactories that specialize in removing labeling on the tops of cheap or non-functional chips, and putting accurately detailed fake labels for expensive chips on instead. (For example, NCP5318 buck regulators relabeled as ATmega328s.)  In short, most of the active SMD parts on a Nano either are genuine and work or obvious fakes that don't work and earn their sellers bad reputations or jail.

The CH340g USB-to-serial chip  vs. ATmega32U4 USB issue is more complicated.  Ie, some may think of the CH340 as a lower quality part than a 32U4.  The CH340 may need a different USB driver than the 32U4 and may not support 57600 BPS serial in some cases. 1, 2.  The ATmega32U4 seems to be available on Alibaba for $0.10 to $.20 in moderate quantities.  I think the CH340g is made only in China and is somewhat cheaper than the ATmega32U4, so its contribution to the BOM total cost may be a few cents.

The PCB probably costs 5 to 10 cents, and assembly is free except for amortized costs of pick and place machines and an IR reflow system with a conveyor.  Boards probably are processed (components placed and soldered automatically) in panels of several dozen units, tested automatically, and then separated for packaging.

Summary: Inexpensive parts and automated processing hold down the per-board costs, moreso than cutting corners on component quality.  Corners may get cut on assembly quality and on quality assurance inspections.


Output clock signal on MKRZERO I have to port a Project written for an Arduino Micro to an MKRZERO.

It communicates via UART with an IC and should also provide a clock signal.

The former code I have used is this:

#define OUTPUTPIN 8
#define CLOCKOUTPIN 5
#define CONTRLEDPIN 13

void Setup() {
pinMode(OUTPUTPIN, OUTPUT);
// Needed for initialization
digitalWrite(OUTPUTPIN, HIGH);
// set clock PIN
pinMode(CLOCKOUTPIN, OUTPUT);
// sets PIN for internal LED
pinMode(CONTRLEDPIN, OUTPUT);

TCCR3A = (1 << COM3A0);
TCCR3B = ((1 << WGM32) | (1 << CS30));
TIMSK3 = 0;
OCR3A = 7;
}

As the MKRZERO uses a different IC the registers are not the same. I've waded through the data sheet document but cannot find something similar.

Does somebody have any experience with the MKRZERO and can help me with this?

The IC on the MKRZERO is an Atmel SAMD21.  Look up the datasheet and read the section on timer counter.  Yes, it's a long document, but you will find all of the information there.


Linear actuator jitters/vibrates when getting PWM from Arduino Mega 2560 through JKR 21v3 motor controller I recently bought this linear actuator and motor controller from Pololu:

Linear actuator
Motor Controller JRK21v3

There are several steps that I have to follow in order to set this thing up before I can test it. These instructions can be found here: Pololu JRK USB Motor Controller User’s Guide » Setting Up Your System

I would like to program this using PWM method because I would like to keep the Serial RX for other sensors.  From my little experiment, by using a potentiometer, I noticed this pattern:

Position: Voltage

Fully extended : 0 V
At Rest : 2.35V
Fully Retracted  : 4.77V.

For this system, I will be controlling it using a PS2 controller. So, by using only the Y_axis of the analog joystick of a PS2 Controller (Up: 0, Rest: 128 and Down: 255), I program it as follows:

//Move Linear Actuator with PS2 on JRK21v3 Controller

#define pwm 6           //red wire
#define dir 7           //yellow wire

//PS2 controller
#include <SoftwareSerial.h>
#include <Cytron_PS2Shield.h>

Cytron_PS2Shield ps2(10, 11); // SoftwareSerial: Rx and Tx pin

void setup()
{
  pinMode(pwm,OUTPUT);

  ps2.begin(9600);
  Serial.begin(9600);
}

void loop()
{
  int Y_axis = ps2.readButton(PS2_JOYSTICK_RIGHT_Y_AXIS);  // 0 - 255
  Serial.print("Y_axis:");
  Serial.println(Y_axis);

  analogWrite(pwm, Y_axis);
}

When I tested it, the linear actuator jitters/vibrates when it is at rest position. What could possibly cause this? Is it the duty cycle due to the PWM? How can I fix this or are there any other better methods?

I got this working using the Servo library.

You set the input method to PWM.
Connect your RX on the motor controller and hook it up to the servo pin.
Connect the ground of the Arduino to the ground of the JRK 21v3.
Then use the knob servo sample by hooking up a pot to a Arduino.
The calibrate the JRK 21v3 by selecting learn.

Now you can use the actuator as a servo.


Reading multiple NTC temperature sensors with Arduino Hej..I am building a project with four NTC 10k ohm temperature sensor with Arduino. It is easy to measure only one NTC temperature sensor. There  is many examples for NTC measurement for example code written with Steinhart-Hart Equation or reading  ADC Thermistor with Lookup Table.

I found one example with Steinhart-Hart Formula.  I am not so good at coding  with Arduino but I Manage and build to write code for only one NTC sensor and read it with Nokia LCD 5110.  The question is how to do code for Multiple NTC sensors?

/* NTC temperature mesurment 13-08-2017
 *
 *  Using Nokia LCD 5110
 */

#include "LCD5110_Graph.h"
LCD5110 myGLCD(8, 9, 10, 12, 11);  // Setup Nokia 5110 Screen SCLK/CLK=5, DIN/MOSI/DATA=6, DC/CS=7, RST=8 Chip Select/CE/SCE=9,
extern uint8_t SmallFont[];
extern uint8_t MediumNumbers[];

int tempPin = 0;   // A0 analog input
int Vout, charTc ;
float R1 = 10000; //otpornost na sobnoj temperaturi 10K ili 10000 oma
float R2, Tk, Tc;
float Ac = 1.009249522e-03, Bc = 2.378405444e-04, Cc = 2.019202697e-07;
char charBuffer[10];

void setup(){
myGLCD.InitLCD(); //initialize LCD with default contrast of 70
myGLCD.setContrast(68);
myGLCD.setFont(SmallFont); // Set default font size. tinyFont 4x6, smallFont 6x8, mediumNumber 12x16, bigNumbers 14x24
myGLCD.clrScr();

myGLCD.print("Temp test",CENTER,0);
myGLCD.print("Check",CENTER,12);
myGLCD.print("Please Wait",CENTER,24);

myGLCD.update();
delay(5000);
myGLCD.clrScr();
}

void loop() {
  Vout = analogRead(tempPin);
  R2 = R1 * (1023.0 / (float)Vout - 1.0); // konvertovanje iz analogne u digitalnu
  Tk = (1.0 / (Ac + Bc*log(R2) + Cc*log(R2)*log(R2)*log(R2))); // Temperature in Klven
  Tc = Tk - 273.15; //temperature converted to celcious

charTc=dtostrf(Tc, 3, 2, charBuffer);

  myGLCD.clrScr();
  //myGLCD.print("Discharging",CENTER,0);
  //myGLCD.print("Temperature:",CENTER,0);
  myGLCD.print("Temp1:",0,0);
  //myGLCD.print( charTc,CENTER,20 );
  myGLCD.print( charTc,36,0 );
  myGLCD.print("Temp2:",0,10);
  myGLCD.print("Temp3:",0,20);
  myGLCD.print("Temp4:",0,30);
  myGLCD.update();
  delay(2000);
  myGLCD.clrScr();
}

As I understand, you have multiple analog sensors you want to read. So your code should look something like this:

// assuming sensors are on A0, A1, A2, Ax

sensorPins [] = {A0, A1, A2};
int sensorNum = 3;

for(int x = 0; x < sensorNum; x++){
  readSensor(x);
}

Something like that should work for you.


How to send float numbers from python3 with struct to arduino I have searched several questions and through google but could not find a solution. I am simply trying to send a float number from python3 with struct to arduino or if there is any other ways other than processing a char array at the arduino side because it is very slow in my opinion..

My arduino code:

void setup() {
  // initialize the serial communication:
  Serial.begin(9600);
}

void loop() {

  unsigned long t = millis();
  float x = analogRead(A3);
  float y = analogRead(A2);
  float c = Serial.read();
  Serial.println(c);
  //Serial.print(t/1000.0);
  //Serial.print(" , ");
  //Serial.print(x);
  //Serial.print(" , ");
  //Serial.println(y);

  // wait a bit for the analog-to-digital converter to stabilize after the last
  // reading:
  //delayMicroseconds(200);
  //delay(2);
  delay(250);
}

My python3 code :

import serial

import struct

arduino = serial.Serial('/dev/ttyACM0', 9600)
data = arduino.write(struct.pack('f', 111.32))
while True:
#    arduino.write(b"123")
    data = arduino.write(struct.pack('f', 111.32))

Getting the serial output as :

163.00
222.00
66.00
215.00
163.00
222.00
66.00
215.00
163.00
222.00
66.00
215.00
163.00

How can i solve my problem ?

EDIT : I changed the arduino code according to the answer the new arduino code is

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

void loop(){
  while(Serial.available() >= 3){

    f = Serial.read() << 24;
    f = ((unsigned long) f) | (Serial.read() << 16);
    f = ((unsigned long) f) | (Serial.read() << 8);
    f = ((unsigned long) f) | Serial.read();
    Serial.println(f);
  }
  Serial.println(f);
}

However, the output is now as such:

ovf
ovf
ovf
ovf
ovf
ovf
ovf
4294941184.00
4294941184.00
4294941184.00
4294941184.00
4294941184.00
4294941184.00
4294941184.00

There is no way around dealing with serial bytewise, since the communication over serial relies on bytes as a unit. You can write the received bytes directly to the float variable. That is faster, than save them to a char array first:

float f = Serial.read() << 24;
f = ((unsigned long) f) | (Serial.read() << 16);
f = ((unsigned long) f) | (Serial.read() << 8);
f = ((unsigned long) f) | Serial.read();

With this the bytes of the float value have to be send with the order from most significant to least significant. I don't know, how the data is formatted, if you send a struct over python. The casting to unsigned long is important here to do the bitwise OR (unsigned long and float have both 4 bytes). (I tried it and it works for me)

Also be aware, that you shouldn't read from Serial, when there is no received byte in the buffer. You can check this with Serial.available(). If there is no new byte in the buffer the Serial.read() function returns an integer with value -1

EDIT:
The code above works, if you transmit the data directly as byte. In your comment you wrote, that you want to write arduino.write(b"111.32") in python. Here you are transmitting an ASCII string representation of the float number 111.32. This is not as fast as transmitting byte data (since you may need way more bytes for one float than 4). In this case you can use either Serial.parseFloat() to get the float from the serial buffer (but ensure, that all bytes for this number have been received with Serial.available()) or you can save the bytes to a string and using String.toFloat() to get the float out of it.

Since you wanted to do it the fast way, you should transmit the numbers as byte data. To do this in python, have a look at the answer of this question. It explains the python code for it (be sure, that you get the ordering of the bytes the same in python and Arduino).


Powering an Arduino UNO through 5V I have a bench supply which I can use to power a breadboard at 5 V. Is it a bad idea to power the the Arduino by going directly to the 5 V pin? It sounds like both this method, and the USB are unregulated, so there would be no difference. Is it safe? Are there any caveats to this?

  5V.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

They say they "don't advise it", but why?

They wouldn't advise it because they provide on board regulation. By feeding it directly you're circumventing their own protection. If however, you're providing your own regulated supply there is no reason why you can't supply it directly.

In a perfect environment, USB should already be regulated. However given the cheap imported USB hubs and plug packs that are available on the market, I would certainly argue that a good bench power supply is no problems in this regards.


Character array weirdness I'm using Energia to program one of TI's MCU. Since Energia is based off the Arduino IDE, I'm hoping someone can help me here.

I'm building a simple UDP packet sender and receiver app. The MCU starts up and connects to the local Wifi network and waits for a packet from another device on the same network.

This packet is collected in a char array char packetBuffer[16];

I want to split this array into two separate arrays each of 8 elements. These are char lampCmdRead[8]; and char pwdReadBuffer[8]; Now the network bit works great. I can send the packet through my desktop and receive it on the MCU. However when I split this array I see that the pwdReadBuffer shows the same contents as packetBuffer even though they are of different sizes. How is this possible?

Here is the code:

char packetBuffer[16];
char lampCmdRead[8];
char pwdReadBuffer[8];

// This is code from the 'void loop()' section
int packetSize = Udp.parsePacket();

if(packetSize) {
 int len = Udp.read(packetBuffer, 16);
 if (len > 0) packetBuffer[len] = 0;
 Serial.println();

 Serial.println("packetBuffer:");
 Serial.println(packetBuffer);
 Serial.println();

 for(ctr = 0; ctr < 8; ctr++) {
   pwdReadBuffer[ctr] = packetBuffer[ctr];
 }
 if (len > 8) pwdReadBuffer[len] = 0;

 for(ctr = 0; ctr < 8; ctr++) {
   lampCmdRead[ctr] = packetBuffer[ctr+8];
 }
 if (len > 8) lampCmdRead[len] = 0;

 Serial.println("pwdReadBuffer:");
 Serial.println(pwdReadBuffer);
 Serial.println();

 Serial.println("lampCmdRead:");
 Serial.println(lampCmdRead);
 Serial.println();
}

And here is the output:

Received packet of size 16
From 192.168.1.101, port 55056

packetBuffer:
2qZ@X51Rredledon

pwdReadBuffer:
2qZ@X51Rredledon

lampCmdRead:
redledon

if (len > 8) pwdReadBuffer[len] = 0;

This line is unsafe.  You declared pwdReadBuffer to be only 8 bytes in size, but this line of code will either do nothing, or write outside of the target buffer, with unpredictable results.

You make a related mistake here:

if (len > 8) lampCmdRead[len] = 0;

First the test should be >= but again, such a value would be beyond the end of the target buffer.

Also consider that if you receive 8 or more characters, you will have no room for a terminating null in pwdReadBuffer, and so cannot pass it to anything that expects a null terminated string.

If you want to use null-terminate storage for a string of up to 8 bytes size, you need 9 bytes of storage.  And of course you need to only use in-range indices to access the elements.


Optmizing print code when writing to file, and reducing print time First things first, I have found some solutions to this problems but they all involved for printing to serial monitor. I am trying to take the information from the sensors and write them to an sd card. Here is my code so far:

//-----Writes Data to SD Card-----//
if(!Data) {
    u8g.firstPage();
    do {
       drawFileError();
    } while( u8g.nextPage() );
    while (1);  // don't do anything more:
}

dcounter++;
if (dcounter=1){

    Data = SD.open("Data.txt", O_CREAT | O_APPEND | O_WRITE);
    Data.println(Header);
    Data.print(strutcDate + "  ");
    Data.print(strutcTime + "  ");
    Data.print(strgpsStatus + "  ");
    Data.print(strmodeIndicator + "  ");
    Data.print(strlatitude + "  ");
    Data.print(strlongitude + "  ");
    Data.print(strspeedOverGnd + "  ");
    Data.print(strcourseOverGnd + "  ");
    Data.print(t);
    Data.print("  ");
    Data.print(f);
    Data.print("  ");
    Data.print(h);
    Data.print("  ");
    Data.print(hi);
    Data.print("  ");
    Data.print(press_pKa);
    Data.print("  ");
    Data.println(str);
    Data.close();
} else{
    Data.print(strutcDate + "  ");
    Data.print(strutcTime + "  ");
    Data.print(strgpsStatus + "  ");
    Data.print(strmodeIndicator + "  ");
    Data.print(strlatitude + "  ");
    Data.print(strlongitude + "  ");
    Data.print(strspeedOverGnd + "  ");
    Data.print(strcourseOverGnd + "  ");
    Data.print(t);
    Data.print("  ");
    Data.print(f);
    Data.print("  ");
    Data.print(h);
    Data.print("  ");
    Data.print(hi);
    Data.print("  ");
    Data.print(press_pKa);
    Data.print("  ");
    Data.println(str);
    Data.close();
}

two questions: is it possible for me to reduce this chunk of code into something smaller? is there a way to decrease print time?

Edit: Ahh I see, the problem with my code is that the last few values are floats.Any way to shorten those as well, or do i need to do it individually? I do agree about the adding string parts.

First of all, the only difference between the two parts of the "if" statement is that, the first time, it prints the header. Instead of that code, you could do this:

//(Include the top part of the code here...)
dcounter++;
if (dcounter=1){
    Data = SD.open("Data.txt", O_CREAT | O_APPEND | O_WRITE);
    Data.println(Header);
}
Data.print(strutcDate + "  ");
Data.print(strutcTime + "  ");
Data.print(strgpsStatus + "  ");
Data.print(strmodeIndicator + "  ");
Data.print(strlatitude + "  ");
Data.print(strlongitude + "  ");
Data.print(strspeedOverGnd + "  ");
Data.print(strcourseOverGnd + "  ");
Data.print(t);
Data.print("  ");
Data.print(f);
Data.print("  ");
Data.print(h);
Data.print("  ");
Data.print(hi);
Data.print("  ");
Data.print(press_pKa);
Data.print("  ");
Data.println(str);
Data.close();

Like already mentioned, you can append strings with the + operator. This would be the final code then:

//(Include the top part of the code here...)
dcounter++;
if (dcounter=1){
    Data = SD.open("Data.txt", O_CREAT | O_APPEND | O_WRITE);
    Data.println(Header);
}
Data.println(strutcDate + " " + strutcTime + "  " + strgpsStatus + "  " + strmodeIndicator + "  " + strlatitude + "  " + strlongitude + "  " + strspeedOverGnd + "  " + strcourseOverGnd + "  " + t + "  " + f + "  " + h + "  " + hi + "  " + press_pKa + "  " + str);
Data.close();

FYI, it doesn't seem like you should close the stream every iteration at the end since you only open it the first time.


find out the pin numbers for the Arduino IDE for a certain board - the esp 32 I followed the tutorial I found here https://techtutorialsx.com/2019/03/29/esp32-arduino-controlling-a-dc-motor/
On the very interesting topic controlling a DC motor with the esp32 and Arduino I have some questions:

The first one: Where in the world did the guy find out the pin numbers for the Arduino IDE for this board? I have no idea how to find them!?

  Taking in consideration that the digital IO pins of the ESP32 can only
  source a maximum current of 40 mA [1], we cannot directly use them to
  control a DC motor.

  Instead, we are going to use a ULN2803A integrated circuit to actually
  provide the current to the motor, while the ESP32 will simply control
  if the motor is running or stopped.

  The connection diagram to control a DC motor from the ESP32 using an
  ULN2803A can be seen below at figure 1. for controlling a DC motor
  with the ESP32, using a ULN2803A integrated circuit

  The controlling of the DC motor with the ESP32 and a ULN2803A IC. In
  short, the ULN2803A will act as a switch, which will turn on / off the
  connection of the motor to GND, depending on the state of the input
  pin labeled as In 1. So, when the GPIO of the ESP32 is at a digital
  high value (VCC), the ULN2803A will connect the motor to GND, and thus
  the motor will be on. When the GPIO is at a digital low value (GND),
  then the motor will be disconnected from GND, and thus it will be off.
  Furthermore, the ULN2803A can be controlled by 3.3 V inputs and
  provide higher voltages, allowing us to control a 5 V DC motor with
  the ESP32.

  The code

  The code for this tutorial will be very simple, since we basically
  only need to control the status (high or low) of a digital pin of the
  ESP32.

  So, we will start by declaring as a global variable the number of the
  pin that will be connected to the DC motor.

  In my case I’ll be using GPIO 13. Note that for the Beetle ESP32
  board, which is the one I’m using, this maps to the pin labeled as D7.

int motorPin = 13;

  After that, we need to initialize the pin as output, in the Arduino
  setup function. To do that, we simply need to call the pinMode
  function.

  This function receives as first argument the number of the pin and as
  second argument a constant indicating the operating mode. So, we will
  pass the as first argument the value of the pin stored in our
  previously declared global variable and as second argument the
  constant OUTPUT.

void setup() {

  pinMode(motorPin, OUTPUT);

}

  We will write the rest of our code in the Arduino main loop. We will
  first turn on the motor, wait some seconds, turn it off, wait some
  more seconds and then repeat.

  So, to turn the motor on, we simply need to set the value of the ESP32
  digital pin to high, which will make the motor run at full speed. We
  can set the digital level of a pin with a call to the digitalWrite
  function.

  This function receives as first argument the number of the pin and as
  second argument a constant indicating the digital level to which the
  pin should be set.

An Arduino boards package with configuration for your board has constants for pins which correspond to labels on the PCB. The constants are defined in pins_arduino.h file, which is applied only if you choose the corresponding board in Tools menu. In code you should use this constants as values for your constants, like for example const uint8_t LED1_PIN = D2;.

If the boards package doesn't have the board and you use generic settings, the you can study the schematics of the board to see which PCB pin goes to which MCU pin. Usually the logical pin numbers are labeled in schematics additionally to physical pin numbers of the chip.

Note: The linked pins_arduino.h is for FireBeetle ESP32. The Beetle ESP32 is not defined in ESP32 boards package yet.

The schematics is on the Wiki page.


How do I run a loop for a specific amount of time? I currently have a for loop that loops 300 times and then moves on.

Instead, I'd like that loop to run for a specific number of minutes, instead.

Here's the current loop, for reference.

for(int i = 1; i<300; i++){
  if (kill() == true){ break; }

  strip.setPixelColor(1, strip.Color(random(100,255),random(100,255),random(100,255)));
  strip.show();

  tone(TONE, notes[random(0,3)]);
  delay(100);
}

Also, I have an RTC that's used elsewhere in the app, so real actual time is available for use if it makes sense to do that...though I'd love to know of a way to do it without an RTC module for future projects.

Here is an example that will run for 5 minutes. Note that the loop will begin executing anytime before the time limit is up, including 1 msec before; it can't cut-off something happening at the 5-minute mark, meaning the timing precision will be limited to the duration of the code in the loop.

Update: My first suggestion had a bug related to the 50-some-odd days roll-over period of the millis() clock. This one is more robust:

uint32_t period = 5 * 60000L;       // 5 minutes

for( uint32_t tStart = millis();  (millis()-tStart) < period;  ){
   doStuff();
   moreStuff();
}


Which sources of randomness are available? I need a souce of randomness to generate a seed to pass to randomSeed. Where can I get this randomness from?

Well, I hear I can read random noise from an unconnected pin.

But I need to connect 9 LEDs and 9 buttons to the board. There seem to be enough pins for this purpose: digital pins 2-13 + analog pins 0-5 makes a total of 18 pins. But does this leave any free pin for a source of randomness?

There are digital pins 0 and 1 left free but I'm reading these should be left free if the board's USB socket is connected and I'm planning to power the whole device by connecting it to a computer through USB. Does this mean I'm supposed to just left pins 0 and 1 unconnected or is it also forbidden to read noise from them?

Or are there any other available sources of randomness? Can I use any other pins for this purpose?

I remember when I was showing this project to the instructor I specifically asked if I have enough pins, noting that I need a source of randomness in addition to 9 LEDs and 9 buttons. He said there are enough pins. Only sadly I forgot to ask how can I read random noise then...

What are my options to somehow obtain a random seed?

Whether you need a source of random noise depends on whether your project needs to not run repeatably. Most experiments - Monte-Carlo simulations, for example, benefit by being able to be re-run. In those cases, you need to be able to re-use the seed, and having an non-reproducible seed (and thus, experiment) is a disadvantage.

If you really need something that runs differently each time you run it, then a seed derived from user reaction time, or from some kind of electrical noise, even reading analog values from a floating input pin, should give you plenty of non-reproducibility.


Encoder coupled with motor shaft.Encoder is giving larger redings than expected I am a rookie and i dont have much experience on arduino. please help me.
I intend to build a robot that will drive on a straight path even on nonuniform surfaces like the ones we see in agricultural fields(It is just a prototype, so i want to run it on normal offroad surfaces).The robot has 4 motors, one for each wheel. I plan to use encoder feedback method to drive straight.
Right now, I have coupled a slotted disc to the shaft of a dc motor and i am trying to get the counts from the encoder and display the count after a certain interval(5 seconds) on serial monitor. The count that i get is way off the mark. The disc is having 30 slots. With just 2 to 3 rotations I am getting a count of around 180.

I am using arduino R3.
Encoder output:- Pin2 (external interrupt)
motor Pins :- 8,9
I am attaching the code below.

const int motorPin1  = 8;  // Pin 14 of L293
const int motorPin2  = 9;  // Pin 10 of L293
const int encoder_pin = 2;
volatile unsigned int count = 0;
 int time1 = 0;
 int time2 = 0;
void setup() {
  // put your setup code here, to run once:
  pinMode(motorPin1, OUTPUT);
    pinMode(motorPin2, OUTPUT);
    pinMode(encoder_pin,INPUT);
    digitalWrite(encoder_pin,HIGH);
    attachInterrupt(0,encoder,RISING);
    Serial.begin(9600);
     digitalWrite(motorPin1,HIGH);
    digitalWrite(motorPin2,LOW);
    time1 = millis();
}

void loop() {
  // put your main code here, to run repeatedly:
    time2 = millis();
    if(abs((time2 - time1) > 5000))
    {
    digitalWrite(motorPin1,LOW);
    digitalWrite(motorPin2,LOW);
    Serial.println(count);
    }
}

 void encoder()
 {
  count++;

 }

the end of code

The disc that i have mounted on the shaft doesn't rotate in vertical plane exactly. But i do get the blinks on the encoder when i rotate the shaft with my hand.Can that misalignment be the reason.

I guess this is a kind of debouncing problem, caused by noise on the interrupt pin. The behaviour might also get worsened by the disalignment you mentioned. You could verify this by manually rotating the shaft, even though you "get the blinks" I doubt they are accurate in count.

If that is the case there are two things you could do:

add a capacity or a RC filter to the interrupt pin to smoothen out voltage peaks if there are some. This will decrease the chance that the interrupt gets triggered accidentially (and will not solve the problem), but as a low pass it also limits the maximum count rate you are able to detect.
implement debouncing in software. This is usually done by ignoring the input signal for a specific amount of time ("deadtime") after an interrupt has occured. As you are expecting a periodic signal and debouncing behaviour might be different at different speed it could be a good idea to capture the time span between two "blinks" and make the deadtime dependend on this calculated speed.

Something else: the way you check for the timestamp is little incorrect. You should instead do something like this:

void setup() {
  unsigned long starttime=millis();
}

void loop() {
  if (millis()-starttime > 5000) {
    starttime=millis();
    // put code here to run every 5000 ms
  }
}


Communication between two Bluetooth modules of two Arduinos I am designing a home automation project. I want to control different home appliances through GSM. I am designing it in such a way that each apparatus is connected to an Arduino and bluetooth module. There is a master unit with Arduino, Bluetooth and GSM modules. When the user sends a message, the GSM receives it and communicates via Bluetooth to the corresponding Bluetooth module and Arduino.

Is it possible to communicate between two Bluetooth modules of two Arduinos? Is there a better solution?

I'm not sure how many bluetooth devices can be connected to your smartphone. But if you use smartphone, the you can eliminate the master Arduino. But as I said, it still depends on the number of devices you'd like to control. This is supposed to go in the comment section.


Arduino UNO not showing up in USB devices on Ubuntu 18.04 I have an Arduino UNO (clone, not original) that was working fine until a couple of days ago. Now, it does not show up when I connect it to my laptop.

Things that I've troubleshouted:

USB cable is fine (tried with another Arduino).
USB ports are fine (tried with another Arduino).
Followed all the fixes and checks listed
here
and everything is successful.
I can upload sketches trough ICSP using a working Arduino.
I've tailed syslog while connecting and disconnecting the failing
Arduino and nothing shows up (it does when using the "good one").
I've tried on a Windows 10 machine and it doesn't show up.

What else can I try?

I can't comment yet but have you updated your board manger for UNO on unbunto?

tools > Board > Board Manger > Search UNO

Kind of dumb to have to do that but it happen to me before and this was the solution I did.


NeoPixel Ring Usage Without Arduino I am looking at purchasing a NeoPixel Ring for a project, but need it to work without an Arduino. Once the NeoPixel has been programmed by the Arduino, will it function when powered without the Arduino? I am not looking at changing colors or anything, I want to set the LEDs to solid red and not change.

I have found in the Adafruit website that it says "NeoPixels don’t just light up on their own; they require a microcontroller (such as Arduino) and some programming." But is this only to get them working initially, or do they require an microcontroller permanently?

No, the settings for the colors are stored in RAM on the individual devices so they need to be reprogrammed every time they are powered on.

On the other hand, it is possible to use a much smaller device such as a surface-mount ATtiny85 to program them, and light_ws2812 runs on said device just fine. And once they have been programmed it is possible to put the MCU in deep sleep so that it consumes almost no power.


how to know which pin is being used, change pin? i am having an issue where i am unsure how my device knows what pins its using. Version #1 is a timeclock which is simply declared with no pin numbers. Version #2 is a simple loop with a device on pin A0;

So how can i set / change the pins for the clock to use. Currently it is on A4 & A5.

If i wanted to move the clock to say pins.. A1 and A2, how would i do that?

Thanks

Version #1-------------------------------------------------

// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 RTC;

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

  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
 //   RTC.adjust(DateTime(__DATE__, __TIME__));
  }

}

void loop () {

    DateTime now = RTC.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
    delay(3000);
}

Version #2---------------------------------------------------------

int powerswitch1 = A0;
void setup()
{
pinMode(powerswitch1, OUTPUT);
}

void loop ()
{

digitalWrite(powerswitch1, HIGH);
delay(500);
digitalWrite(powerswitch1, LOW);
delay(500);
digitalWrite(powerswitch1, HIGH);
delay(500);
}

Your confusion is over the multiple functions of analog pins A4 and A5.

In addition to being analog pins, they are also the pins configured internally for I2C/TWI serial, which is interfaced with using the Wire library on arduino. Since those are the only two pins Wire can use, there is no need to specify them, the sketch just calls Wire.begin() to set everything up.

If you need a second I2C device you can simply connect them both up to A4 and A5 at the same time, the protocol is designed to support that kind of thing. If you need to use A4 and A5 for something else besides I2C, you can't continue to use the hardware I2C library.

It is possible to use a software implementation of I2C/TWI serial on other pins, but usually soft-serial implementation have some drawbacks compared to the hardware version. There is an implementation on the arduino playground here: http://playground.arduino.cc/Main/SoftwareI2CLibrary

That said, the RTC library you are using seems to internally use the Wire library, so it would take some hacking to switch it to a different I2C implementation.


Using same GPIO pins to control multiple stepper drives I have an Arduino Mega 2560 and I want to control four 23-frame steppers same speed/direction for a conveyor application. I want these to be synchronized exactly as possible for smooth operation.

Can four TB6600 drivers be daisy chained to the same Arduino GPIO pins?

Is there a limit to how many number of drivers I can daisy chain?

I'm wondering about current draw from the 5 volt Arduino GPIO, spread out over many drivers.

Thanks for your help!
Bob

Those devices use opto-isolated inputs. To all intents and purposes they look just like an LED with a resistor in series.
The built-in resistor looks like it sets the current to "between 8mA and 15mA" and typically 10mA, though it's impossible to say what it actually is.  So we'll take the worst-case scenario of 15mA.
The Arduino has an absolute maximum of 40mA, and a recommended maximum of 25mA from each IO pin, with a maximum of 200mA in total through all pins.
That means you ideally can't really have more than one TB6600 per IO pin, but you could get away with 2 per pin, certainly no more.
To run lots in parallel you would need a separate set of drivers that can "fan out" the low-current signal to either a single high current signal or a parallel set of low-current signals.
It looks like you provide 5V to one pin of each input (the anode of the opto-isolator) and sink the current through the other pin (the cathode of the opto-isolator) to ground through your IO pins. That means you could use a single large N-channel MOSFET to sink all of the cathodes in parallel and invert your IO logic in software.


Rfid reader and SD card shield won't work together I recently encountered a problem that's been bugging me for days. I want to make a project using a RFID reader and log data on an SD card with an Arduino Nano, but apparently no matter what I do, I can't seem to make them work together on SPI. They both work individually, and the SD shield works in parallel with the RFID reader, but the RFID doesn't work in parallel with the SD shield.

I'm absolutely sure that the wiring is correct, slave select on both modules are wired to different digital pins, and both are connected through bidirectional level shifters.

I noticed that the RFID reader works fine when I disconnect the MISO pin from the SD shield. I tried putting a diode between SD MISO and digital pin 12, I tried adding pullup resistors on both SS pins, I tried adding resistors on MISO lines, I tried pulling HIGH the SS i don't use, and low the one I want active. Nothing seemes to work and I'm out of ideas. The last thing I will try is conencting the modules on separate VCC, but I don't have faith that it will make any difference.

I hope someone has some advice for my problem.

Thanks in advance

SD cards (or really their breakout boards) don't tend to obey the rules with regards to SPI. In particular the MISO pin isn't set to high impedance when the slave select is not selected.

You can fix this with a tri-state buffer that you feed the SD card's miso line to and controlled by the slave select. The output from the buffer goes to the arduino's MISO.


Mega 2560 Doesn't Respond When trying to upload to my Mega r2, it simply times out during uploading.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

I tried burning the bootloader, but that also gave an error.

Error while burning bootloader.
avrdude: usbdev_open(): did not find any USB device "usb"

I can see the arduino in my Devices and Printers in control panel, so I don't think the board is burnt.  The power light also is on.  Any ideas?

I have seen this error numerous times before. I think the possibilities could be that either some external device is connected on RX, TX pins of arduino mega or mega is not getting sufficient power. Some connection from your board is trying to pull more than the limit current.

and off course the answers suggested above are also right. check out every possibility.


Is setting AVR TWCR for mega328p TWEN in each function necessary? I found this useful website explaining for to configure and implement the TWI for mega328p, but what I found not so obvious is that in the website they set TWEN in every function, while in the datasheet C code example, they only set it in START and STOP functions.

I also find another style in Arduino Wire library, that they implement more easier functions for starting and ending the module.

This is the website, could anyone take a look and tell me if setting TWEN in each function is necessary?

Also, is it necessary to check for TWINT after sending STOP command?

http://www.embedds.com/programming-avr-i2c-interface/

Regards,

The big difference is interrupt driven or busy wait implementation of the TWI hardware module protocol. Enabling interrupts is necessary in an interrupt driven implementation while busy wait should not enable interrupts.

A busy wait implementation is much simpler but it cannot be asynchronous. An interrupt driven implementation can be asynchronous and even power down the rest of the MCU during the TWI communication. It should be noted that the Arduino Wire class is interrupt driven but synchronous.

Cheers!


The voltage level fluctuates whenever ESP8266 receives signal Good afternoon dear community,

I am trying to built a WiFi communication with Arduino using ESP8266 module. There is one servo, one step motor connected to Arduino and whenever the ESP8266 Wi-Fi module receives a signal, the voltage level on the motor and servo fluctuate dramatically, which causes inaccurate results on how motor and servo behaves. I have connected the ESP8266 module using SoftwareSerial, and even when the signal is not transferred into motor or sevo, the voltage levels change whenever a data is received by the WiFi module.

Below is my code,

#include <Servo.h>
#include "SoftwareSerial.h"
SoftwareSerial softSerial(10, 11); // RX, TX

// Components:
Servo servo1;
Servo firstESC;

// Motor:
const int MAX_SPEED = 1850;
const int MIN_SPEED = 1200;
int armValue = 1500;
int speedIncrease = 20;
int speedDecrease = speedIncrease * 3;

// Direction:
int currentPos;
const int MAX_ANGLE = 120;
const int MIN_ANGLE = 60;
const int MID_ANGLE = 90;

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

   softSerial.begin(9600);
   // softSerial.setTimeout(10);

   // Setup servo:
   servo1.attach(9);
   servo1.write(90);

   // Setup direction:
   Serial.println("The motor is arming in 2 seconds, please wait.");
   firstESC.attach(8);

   // Arm the motor after 2 seconds:
   delay(2000);
   firstESC.writeMicroseconds(armValue);

   Serial.println("Serial is setting up, wait time: 3000 ms.");
   delay(3000);

   // Check board communication:
   softSerial.println("AT");
   delay(1000);
   while (softSerial.available()) {
     String message = softSerial.readString();
     Serial.println(message);
     delay(1000);
   }

   // Connect to WIFI:
   Serial.println("Connecting to wifi, wait time 4000 ms.");
   softSerial.println(--- COMMAND TO CONNECT WIFI ---);
   delay(4000);
   while (softSerial.available()) {
     String message = softSerial.readString();
     Serial.println(message);
     delay(1000);
   }

   // Wait for connection to be stable:
   delay(2000);

   // Get IP address:
   Serial.println("Requesting IP Address.");
   softSerial.println("AT+CIFSR");
   delay(2000);
   softSerial.println("AT+CIPMUX=1"); // Set multiple connection available.
   while (softSerial.available()) {
     String message = softSerial.readString();
     Serial.println(message);
     delay(1000);
   }

   delay(2000);

   // Set up server:
   Serial.println("Connecting to server..");
   softSerial.println("AT+CIPSTART=3,\"TCP\",\"192.168.1.67\",1235");
   delay(2000);
   while (softSerial.available()) {
     String message = softSerial.readString();
     Serial.println(message);
     delay(1000);
   }

   Serial.println("Set up is complete, loop started.");

}

String inString = "";
bool reading = false;

void loop() {

   while (softSerial.available() > 0)
   {
    char inChar = softSerial.read();

    if(inChar == 'O') {
      reading = false;
    }

    if(reading) {
      if (inChar == ','){
        Serial.println(inString);
        int val = inString.toInt();

        //Motor input
        if (val >= MIN_SPEED && val <= MAX_SPEED){
          setSpeed(val);
        }

        //Direction input
        else if (val >= MIN_ANGLE && val <= MAX_ANGLE ){
          setRotation(val);
        }
        inString = "";
      }
      else{
        if(inChar !='\0' && inChar != '\n' ){
          inString += inChar;
        }
      }
    }

    if(inChar == ':') {
      reading = true;
    }

   }

   if (Serial.available())
   {
      String message = Serial.readString();
      // Serial.print(message);
      setSpeed(message.toInt());
   }
}

void setSpeed(int customSpeed){
  firstESC.writeMicroseconds(customSpeed);
}

void setRotation(int angles){
  servo1.write(angles);
}

The ESP8266 is notoriously noisy, chiefly because the cheap boards the ESP8266 is commonly sold on don't implement any form of power filtering.

So you really have to add your own.  As I had to recently when adding an ESP8266 board to an audio system.

For that I came up with this schematic:

VCCA is your main incoming power.  VCCD feeds the power into the ESP8266. The motors are connected to the same point as VCCA.


I have 4 motors connected to their own ESC (that is connected to a power distribution board), how do I connect this to Arduino uno? (Drone) I am currently working with a bigger drone that I want to connect with an arduino uno.

The motor and ESC that are already soldered together and connected are these: https://hobbyking.com/en_us/mt1806-brushless-combo-include-esc-5030cw-ccw.html

I have also connected it to a power distribution board where I succesfully can connect my 3s lipo battery.

What is currently missing is where I should put the 3 pins on each ESC onto the arduino board. So there are 12 pins in total.

The color on the 3 wires on each ESC are: yellow, red and brown.

Yellow is the signal if i am not mistaken and those should be connected on the PWM pins where I control each motor in the code.

When it comes to the red it is + power and should I ignore to connect these pins? I would like for my battery to power both the motors and the arduino so of course I would prefer to connect it to the arduino uno if it is possible.

Here are just some clarifications for you:

Signal pins don't have to be connected to PWM pins. AFAIK, any digital pins should work.
All grounds togheter! Glad you got that right!
Connect VCC of ESCs directly to the power supply.
Connect power supply to VIn of Arduino (not 5V because you are going to grill it!)

Uptdate

Yes, you can probably solder all the VCC wire of the ESCs togheter.
By power supply, I meant connecting it directly to the battery.

To power the Uno, connect the battery+ to the VIn pin of the UNO.


Can an ultrasonic sensor differentiate b/w objects? Can we potentially use an ultrasonic sensor to differentiate between objects based on the reflective capacity of the object?
For example to differentiate between metals and biodegradable wastes.

No. No, you can't. All they sense is the "time of flight".

The closest you would come would be to have a sensor which can detect physical properties of the target.  That could be colour, sound absorption, etc.  You'd need something that sends out a "broad spectrum" signal (white light, white noise, etc) and detects the reflected spectrum (colour sensor, wide-band microphone) and do spectral analysis of it.  The signal would also have to be fairly tightly focussed to exclude signals from the environment.

All-in-all not something for a little Arduino to consider without lots of extra expensive hardware.


Questions on programming logic? So I am learning arduino code by going through examples and playing with them, and I came across something interesting. I am not fluent in any coding language but I am fully familiarized with computer logic and function so I can read what you suggest just fine.

What I want to know is, why are these two code pieces different?

const int ledPin =  13;

int ledState = LOW;

long interval = 1000;

void setup() {

pinMode(ledPin, OUTPUT);
}

void loop()
{

  unsigned long currentMillis = millis();

  if(currentMillis > interval) {

    currentMillis = 0;

    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    digitalWrite(ledPin, ledState);
  }
}

This is my code, or rather modification to this code:

const int ledPin =  13;

int ledState = LOW;
long previousMillis = 0;

long interval = 1000;

void setup() {

  pinMode(ledPin, OUTPUT);
}

void loop()
{

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis > interval) {

    previousMillis = currentMillis;

    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    digitalWrite(ledPin, ledState);
  }

}

How is it that the first code works, and the second code turns the led on and either terminates or never turns the LED off? The code is designed to blink the LED once every 1 second.

Ah yes, this problem.

Note the declaration of currentMillis:

unsigned long currentMillis = ...;

And now note the declaration of previousMillis:

long previousMillis = ...;

You wouldn't think that one little word could make that much difference, but it does. It completely changes how C performs mathematics. previousMillis must also be unsigned or you will get undesired results.


motor affecting time calculation between hardware interrupts My robot uses an Arduino Mega 2560. It has 6 IR receiver modules connected to its 6 external pins namely 2, 3, 18, 19, 20, and 21.I have connected the Pololu MC33926 dual motor driver arduino shield to my arduino(here is the connections diagram : https://www.pololu.com/docs/0J55/3.c ). I generate a 56KHz IR signal with an LED from another Arduino. The IR receiver modules convert the 56KHz signal into a active low digital signal. My signal consists of a signature bit followed by 32 bits of data. a binary 1 is represented by a signal of length 1200 uS and a binary 0 is represented by a 600uS signal with intervals of 600uS. I employed a state machine in my code which checks the duration of time between falling edge and rising edge. and vice versa and compares it to the duration expected. If anything is not expected it discards as noise and goes back to the idle state. If the duration is as expected it goes to the next state and then takes in the entire 32 bits and converts this binary format into a decimal value. I print this value on a 7 segment display on my robot. It works perfectly when the motor's are not running.
      Now this is the case when the motors are running. It does not receive the signal. I have tested every component individually and these are the results:

The receivers still receive the signal perfectly, and their output to the Arduino is also as expected. No problem there.
Earlier the Arduino was being powered through the Motor driver. Just to make sure that was not the problem I separated the Arduino's power supply from that of the motor driver. Still the same issue, i.e. the robot does not receive a valid signal(at this point i realized the arduino receives a valid signal but isnt able to decode it accurately).
We then printed out the values of time differences between each rising and falling edge on the interrupt pins. These values seem correct and within the tolerance range when the motors are switched off. But when the motors are switched on these values are not right. Of the 32 duration's measured, atleast two are not right(for eg. instead of 300 uS it calculated 88uS) due to which the signal is being discarded as invalid.
I thought that the PWM being generated to control the speed of the motors on digital pin 9 and digital pin 10(OC2B AND OC2A). Even though the PWM signals were being generated(without the motors connected) the signal was still being read as valid and the robot was receiving the signal. So its not that either.

The only anomaly I have found are the readings of the durations of the interrupt intervals. Can somebody please tell me what connection I have done wrong. Its mostly not with the program since it works otherwise. Something with the motor is making the Arduino act weirdly. Any help will be greatly appreciated. I have to scale up these robots to build a swarm and I am still stuck in the first step.

Thanks a lot.

Noise from electromagnetic sources is always an important issue that must be addressed. The aims are to minimise noise generation at source, reduce transmission of noise between source and the "target" affected circuitry and reduce noise impact at the target.

Motor controller circuit diagram here

The shield power supply link MUST have been removed.
Shield must have all own powering.
Coupling via a common eg 5V supply has a high chance of being problematic.
The two 5V supplies (arduino & shield) could have a common higher voltage source but need separate regulators and proper noise removal in each supply.

Placing extra capacitance across the arduino Vin or main power source MAY help.

I assume that the motors are driven in either direction during operation. If not then a reverse diode across the motors should help.
If bidirectional,  try reversed diodes from each motor lead to Vout (= V+ motor drive voltage).

The shield's Vout filter capacitors C7 & C8 care 47 uF each.
Vout could usefully have 1000 or so uF added somewhere on the board.

I do not know how much motor current is drawn and exact control strategy. This MAY interfere with motor drive but probably not: Identify one motor which "has issues". Add a small series resistance in each lead with a capacitor across the leads on the motor side. Here "small" means "does not noticeably affect performance". eg 1 Ohm if Imotor < to << 1 amp. Capacitor needs to be biplar for bidirectional motor control - eg a 1 uF ceramic or plastic (polyester, mylar, ...) cap.

'If all else fails'[tm] opto coupling the driver interface is possible BUT should not be needed.

Try above.
Report.
Ask more questions if needed.


How do I make my LCD screen scroll text while allowing for button input? Here's what I want my code to do: This is part of a tea infusing project that would automate the steeping of tea, part of this is initially having a selection of either Black/Herbal tea or White/Green tea, this will then set off several other factors down the timeline.
I want my LCD screen to display and scroll "Please select a tea" while still being able to take in pushbutton input.
I've been doing this all day, and I've tried several things. I firstly tried using a normal delay function so my text could scroll properly, but the problem with that is that it halts all the code and doesn't allow for any other input, so I quickly found millis() was likely what I needed to use. However, when I try to apply it to this specific example, it just scrolls all my text extremely quickly through the LCD.
Perhaps I'm being stupid and ignoring something obvious, but please let me know.

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 16, 2);

const int black_herbal_osb = 2;

int black_select;

//Timing
unsigned long prev_millis;
unsigned long current_millis;
const unsigned long LCD_delay = 500;

void setup() {

  //Tea selection buttons
  pinMode(black_herbal_osb, INPUT);

  //LCD screen setup
  lcd.init();
  lcd.backlight();

}

void loop() {

  lcd.autoscroll();
  lcd.setCursor(16, 0);
  lcd.print("Please");

  current_millis = millis();

  black_select = digitalRead(black_herbal_osb);

  if (black_select != HIGH) {

    if (current_millis - prev_millis >= LCD_delay) {
      lcd.print(" select ");
      prev_millis = current_millis;
    }
    if (current_millis - prev_millis >= LCD_delay * 2) {
      lcd.print("a ");
      prev_millis = current_millis;
    }
    if (current_millis - prev_millis >= LCD_delay * 3) {
      lcd.print("tea ");
      prev_millis = current_millis;
    }
  }

  else if (black_select == HIGH) {
    lcd.clear();
    lcd.autoscroll();
    lcd.setCursor(16, 0);
    lcd.print("Black/Herbal ");
    delay(500);
    lcd.print("tea ");
    delay(500);
    lcd.print("selected");
    delay(2000);
    lcd.noAutoscroll();
    lcd.clear();
  }

}

See my answer to a similar question - about motors but the idea is the same. You call a function for each piece of the job that needs to be done. The function itself decides whether it needs to be done yet, and if so, does it and returns, otherwise it just returns. The loop() function just calls all your other action functions and does nothing else -- all of the real work takes place in those functions.
Looking at your scrolling code, I think one function could print successive pieces of the message by remembering what did last. Another could read and debounce the button(s) and save its/their state.
And once you get to controlling the infusing process, one (or maybe more) functions could be used to control that.


Having really weird experience with string concat Having really bad day with concat. I'm not quite sure where i did wrong..
Have a look at my function below.

void sim900aSendHttp(String bid, String lati, String longi) {
  Serial.println("BUSID:"+bid+",LAT:"+lati+"LONG:"+longi);
  String httpget = "http://uumresearch.com/bustracking/update_location.php?busid="+bid+"&latitude="+lati+"&longitude="+longi+"";
  //String httpget = "http://uumresearch.com/bustracking/update_location.php?busid=KDF8860&latitude=6.533415&longitude=106.33345";
  Serial.println(httpget);
  serialSIM800.println("AT+HTTPPARA=\"URL\",\"" + httpget + "\"");
  delay(3000);
  serialSIM800.println("AT+HTTPACTION=0");
  delay(8000);
}

The problem is with:

String httpget = "http://uumresearch.com/bustracking/update_location.php?busid="+bid+"&latitude="+lati+"&longitude="+longi+"";

where serial monitor only  shows

http://uumresearch.com/bustracking/update_location.php?busid=KDF8860

missing "lat" and "longi" variables in the string concat.

Both variable confirmed available to the function as printed by

Serial.println("BUSID:"+bid+",LAT:"+lati+"LONG:"+longi);

+ on const char * increments the pointer. only String has + overloaded as concatenation of the right operand (not left). so "abc" + str + "efg" will not work even if str is String. What will work is String("abc") + str + "efg", but small Strings will fragment the heap memory of the MCU very fast and the sketch will crash.

Print the parts directly to serialSIM800 or use snprintf to build the strings or try CStringBuilder from my StreamLib


Can I use NodeMCU with Arduino to connect to wifi or do I need a separate module? I am just starting out with electronics. I got a Arduino Mega 2560 board and am able to do simple things like blink. Now I want to start a project on IoT and want to connect this board with internet. I got some leads here. While googling ESP8266, I came across NodeMCU which has a processor too. I already have Arduino, so can I use only the wifi module of NodeMCU and connect it to Arduino?

NodeMCU already has a processor built in with the WiFi so you don't need a separate processor. If you just want to add WiFi to your Arduino board use an ESP8266 board connected to the Arduino. That is essentially the WiFi part of NodeMCU.


How does ESP8266 work as web server with Arduino? I am trying to learn internet of things with smart home. I will connect an ESP8266 and an Arduino with the IBM Bluemix server to control a circuit from a public IP.

I want to start with the local network for now. I have gone through a couple of links which seem like a great start http://allaboutee.com/2014/12/30/esp8266-and-arduino-webserver/

They explain how it works, and have source code but no circuit diagram. How should I connect the ESP8266 with Arduino for this example ?

#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
const byte txPin = 3; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial esp8266(rxPin,txPin);

void setup() {
  Serial.begin(9600);
  esp8266.begin(9600);
  delay(1000);
}

void loop() {
  Serial.println("Sending an AT commands");
  esp8266.println("AT");
  delay(30);
  while(esp8266.available()) {
    String data = esp8266.readStringUntil('\n');
    Serial.println("Got response from esp8266: " + data);
  }
}

The exact same way as any other ESP8266 example. The fact that you are using it as a web server doesn't change how you wire it.

For that specific code snippet it even tells you in the comments:

// 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


Using a button to cycle an array So. I would like to cycle through an array using a button. My current code goes through if statements when the button is pushed. In each if statement I have a loop to print out a list of strings. I am curious if there is anyway to directly cycle through an array using buttons instead of this indirect route I have taken.

Last question - Is there a way to set the indents in the Arduino IDE to make formatting easier here?

//------------------------------------------------------------------------------------------------
// Displays information when a push button is pressed. Also turns on and off a corresponding led.
// 5/3/2016
//------------------------------------------------------------------------------------------------

// declare variables

char* titles[] = {
  "RELATION",
  "FIRST NAME",
  "LAST NAME",
  "LOCATION",
  "PHONE NUMBER"
};
char* user_info[] = {
  "SELF",
  "JOHN",
  "SMITH",
  "FLORIDA",
  "999-888-6666"
};
char* econ_one[] = {
  "BROTHER",
  "MICHAEL",
  "SMITH",
  "FLORIDA",
  "999-888-5555"
};
char* econ_two[] = {
  "WIFE",
  "EMILY",
  "SMITH",
  "FLORIDA",
  "999-888-4444"
};
char* econ_three[] = {
  "SISTER",
  "SOPHIA",
  "ADAMS",
  "NEW YORK",
  "888-777-3333"
};

int ledPinOne = 2;
int ledPinTwo = 3;
int ledPinThree = 4;
int ledPinFour = 5;
int buttonPin = 6;
int state = 0;
// setup - set pins

void setup() {
  Serial.begin(9600);
  pinMode(ledPinOne, OUTPUT);
  pinMode(ledPinTwo, OUTPUT);
  pinMode(ledPinThree, OUTPUT);
  pinMode(ledPinFour, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.println("Emergency Contact");
}

// main
void loop() {
  if (digitalRead(buttonPin)) {
    if (state == 0) {
      int x;
      for (x = 0; x <= 4; x++) {
        Serial.println(" ");
        Serial.print(titles[x]);
        Serial.print(" ");
        Serial.print(user_info[x]);
      }
      Serial.println(" ");
      setLights(HIGH, LOW, LOW, LOW);
      state = 1;
    } else if (state == 1) {
      int y;
      for (y = 0; y <= 4; y++) {
        Serial.println(" ");
        Serial.print(titles[y]);
        Serial.print(" ");
        Serial.print(econ_one[y]);
      }
      Serial.println(" ");
      setLights(LOW, HIGH, LOW, LOW);
      state = 2;
    } else if (state == 2) {
      int z;
      for (z = 0; z <= 4; z++) {
        Serial.println(" ");
        Serial.print(titles[z]);
        Serial.print(" ");
        Serial.print(econ_two[z]);
      }
      Serial.println(" ");
      setLights(LOW, LOW, HIGH, LOW);
      state = 3;
    } else if (state == 3) {
      int q;
      for (q = 0; q <= 4; q++) {
        Serial.println(" ");
        Serial.print(titles[q]);
        Serial.print(" ");
        Serial.print(econ_three[q]);
      }
      Serial.println(" ");
      setLights(LOW, LOW, LOW, HIGH);
      state = 0;
    }
    delay(1000);
  }
}

// function to turn LEDs on/off

void setLights(int one, int two, int three, int four) {
  digitalWrite(ledPinOne, one);
  digitalWrite(ledPinTwo, two);
  digitalWrite(ledPinThree, three);
  digitalWrite(ledPinFour, four);
}

output image

https://www.dropbox.com/sc/fwll0qe7cyye1mt/AAD5vI9buU_X0bl04KXFAQyja

I would recommend using multidemnsional arrays for both your contacts and your light states.

//------------------------------------------------ declare variables

char* titles[] = {"RELATION", "FIRST NAME", "LAST NAME", "LOCATION", "PHONE NUMBER"};

char* econs[][5] = {
  {"SELF", "JOHN", "SMITH", "FLORIDA", "999-888-6666"},
  {"BROTHER", "MICHAEL", "SMITH", "FLORIDA", "999-888-5555"},
  {"WIFE", "EMILY", "SMITH", "FLORIDA", "999-888-4444"},
  {"SISTER", "SOPHIA", "ADAMS", "NEW YORK", "888-777-3333"}
};

uint8_t lights[][4] {   {HIGH, LOW, LOW, LOW},
  {LOW, HIGH, LOW, LOW},
  {LOW, LOW, HIGH, LOW},
  {LOW, LOW, LOW, HIGH},
};

int ledPinOne = 2;
int ledPinTwo = 3;
int ledPinThree = 4;
int ledPinFour = 5;
int buttonPin = 6;
int state = 0;

//------------------------------------------------ setup - set pins
void setup() {
  Serial.begin(9600);

  pinMode(ledPinOne, OUTPUT);
  pinMode(ledPinTwo, OUTPUT);
  pinMode(ledPinThree, OUTPUT);
  pinMode(ledPinFour, OUTPUT);
  pinMode(buttonPin, INPUT);

  Serial.println("Emergency Contact");
}

//------------------------------------------------ main
void loop() {

  if (digitalRead(buttonPin))
  {
    if (state > 3)
      state = 0;

    {
      for (int y = 0; y <= 4; y++)
      {
        Serial.println(" ");
        Serial.print(titles[y]);
        Serial.print(" ");
        Serial.print(econs[state][y]);
      }

      Serial.println(" ");
      setLights(lights[state][0], lights[state][1], lights[state][2], lights[state][3]);
    }

    delay(1000);
    state++;

  }

}

//------------------------------------------------ function to turn LEDs on/off

void setLights(int one, int two, int three, int four)
{
  digitalWrite(ledPinOne, one);
  digitalWrite(ledPinTwo, two);
  digitalWrite(ledPinThree, three);
  digitalWrite(ledPinFour, four);
}

I haven't tested the above, but it should provide the same result.

As for the second part of your question, there is an autoformat tool in the Tools menu that will auto-indent your code. Ctrl-T will do the same.


Freeduino avrdude stk500_getsync() not in sync I have a Freeduino USB 1.1 board with atmega 8l-8pu microcontroller on it. When I try to upload program, it shows error:

avrdude stk500_getsync() not in sync: resp 0x00

I have tried reset and the red led blinks which I think suggest bootloader is working fine.

On Arduino IDE, I have set Arduino Uno and correct port which is shown in device manager.

One weird problem that I noticed is that no matter which USB port I connect to, it says COM9 on device manager. Is that something to look into?

Any ideas?

There could be many reasons for the problem you have got.

1) Try to program your Board with any other device you have got. If you are trying to program it with PC try to do it using Laptop.

2) Plug your board to any other port. Then Right Click My Computer and Select Manage--> Device Manager and find the port where your Freeduino is connected. Then Select that port in  your Arduino IDE.

Solution 1 worked for me!


Array variable name changes from readings1 to readings2 I've been using two MB1240 Ultrasonic Sensors with analogRead, and have found that after using bubble sort, the array is found in array readings2, and not readings1. This is important because I would like to find the distance from each sensor.

Below is the code I've put together that uses buttons to determine when each sensor should be triggered.

const int anPin1 = 1;
const int anPin2 = 2;

const int triggerPin = 2;
long anVolt1, anVolt2;

// button Pins
const int buttonPin1 = 11;
const int buttonPin2 = 13;

int buttonState1;
int buttonState2;
int lastButtonState1 = false;
int lastButtonState2 = false;

long lastDebounceTime1 = 0;
long lastDebounceTime2 = 0;
long debounceDelay = 50; //ms

// initialise averaging array
const int numberOfReadings = 10; // reasonable DOF
long readings1[numberOfReadings];
long readings2[numberOfReadings];
long median;

void setup() {
  Serial.begin(9600);
  pinMode(triggerPin,OUTPUT);
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  delay(200); // Datasheet: Sensors require 175 ms to calibrate
}

void start_sensor(){
  digitalWrite(triggerPin,HIGH);
  delay(10);
  digitalWrite(triggerPin,LOW);
}

long read_sensor1(){
  //Used to read in the analog voltage output that is being sent by the XL-MaxSonar device.
  //Scale factor is (Vcc/1024) per centimeter. A 5V supply yields ~4.9mV/cm for standard range sensors
  anVolt1 = analogRead(anPin1);
  return anVolt1;
}

long read_sensor2(){
  anVolt2 = analogRead(anPin2);
  return anVolt2;
}

void printall(long readings[]) {
  int med = numberOfReadings/2;
  median = (readings[med-1] + readings[med])/2;

  Serial.print("Sensor: ");
  for (int i = 0; i < numberOfReadings; i++) {
    Serial.print(readings[i]);
    Serial.print("cm ");
  }
  Serial.println();

  Serial.print("Median: ");
  Serial.print(median);
  Serial.println(" cm");
}

void loop () {
  int reading1 = digitalRead(buttonPin1);
  int reading2 = digitalRead(buttonPin2);

  // for noise
  if (reading1 != lastButtonState1) {
    lastDebounceTime1 = millis();
  }

  // for noise
  if (reading2 != lastButtonState2) {
    lastDebounceTime2 = millis();
  }

  if ((millis() - lastDebounceTime1) > debounceDelay) {
    if (reading1 != buttonState1) {
      buttonState1 = reading1;
      if (buttonState1 == HIGH) {
        for (int i = 0; i < numberOfReadings; i++){
         start_sensor();
          readings1[i] = read_sensor1();
          delay(150); // From datasheet: Period = 99ms
        }

            **// bubble sort with flag
        for (int i = 0; i < sizeof(readings1)-1; i++) {
            bool flag = true;
            for (int j = 1; j < sizeof(readings1)-1; j++) {
                if (readings1[j-1] > readings1[j]) {
                    int t = readings1[j-1];
                    readings1[j-1] = readings1[j];
                    readings1[j] = t;
                    flag = false;
                }
            }
            if (flag) break;
        }
       printall(readings1);**
      }
    }
  }

  lastButtonState1 = reading1;

  if ((millis() - lastDebounceTime2) > debounceDelay) {
    if (reading2 != buttonState2) {
      buttonState2 = reading2;
      if (buttonState2 == HIGH) {
        for (int i = 0; i < numberOfReadings; i++) {
          start_sensor();
          readings2[i] = read_sensor2();
          delay(150);
        }
       printall(readings2);
      }
    }
  }
  lastButtonState2 = reading2;

  //clear previous readings
  memset(readings1, 0, sizeof(readings1));
  memset(readings2, 0, sizeof(readings2));
}

Scenario: I have clicked the first button to return a reading from the first sensor, and I am expecting the results to be stored then sorted in array readings1. After the bubble sort, if I enter printall(readings1), it returns an array of zeros, but if I use a printall(readings2), it returns the sorted array I expected.

I can't find where I'm going wrong with this one, any help would be greatly appreciated. Thank you!

for (int j = 1; j < sizeof(readings1)-1; j++) {

sizeof(readings1) is not the number of elements in the array, it is the size of the array in bytes (in your case, 40). You are exceeding the bounds of the array. You know the number of items (numberOfReadings) - why not use that?


WS2812B are only white on custom board I recently designed a board for an LED project. I am using WS2812B as the LED, and an ATMEGA328P-AU as the microcontroller. I also am using an arduino nano as my ISP and using "flash with programmer". When I flashed the FastLED blink example (Code below) the LED lit up as white and stayed white when it was supposed to flash red. I tried various examples and they all had the same outcome, just white. Am I missing a crucial component in my circuit (aside from some decoupling capacitors)? Is it a software problem?
#include <FastLED.h>

#define NUM_LEDS 1
#define DATA_PIN 5

// Define the array of leds
CRGB leds[NUM_LEDS];

void setup() {
     FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);  // GRB ordering is typical
}

void loop() {
  // Turn the LED on, then pause
  leds[0] = CRGB::Red;
  FastLED.show();
  delay(500);
  // Now turn the LED off, then pause
  leds[0] = CRGB::Black;
  FastLED.show();
  delay(500);
}

The WS2812B chips are very sensitive to timing. They rely on pulses being just the right length for things to work.
It is common if the timing is off that you just end up with white.
Since you have a blank chip that you have never put a bootloader on the fuses will be set wrongly for your configuration. By default a chip comes configured for the internal 8MHz oscillator. That means that everything will be running at half the speed.
You need to set the fuses to use the 16MHz crystal so that it matches the F_CPU setting of 16000000 in the board configuration. Either that or use a board configuration that expects to run at 8MHz.


how can i conect a lipo charger to a teensy 4.0? I have the battery charger product https://www.adafruit.com/product/2124
and a teensy 4.0, that I would like to use to power it.
what, if any pin would I connect from bat, to the teensy?
Its my understanding that the Lion backpack is a voltage regulator, and thats it. it takes Vin, ground, and Vout.
I understand the 5v output goes to the 5volt pin of the teensy.
the gnd goes to gnd. should Vin go someplace? Or should I leave it off?
Please assist.

The output voltage of the charger board is marked with BAT. You should connect it to the Vin pin of the Teensy, which then will convert the batteries 3.7-4.2V down to 3.3V.

Of course you need to connect the grounds of the charger board and the Teensy (on the charger board ground is marked with G).

The 5V pin on the charger board is no output. The board does not give you 5V. This is actually the pin for the charging voltage, which is 5V. Here it depends on how you want to charge the battery. If you use an external source, you can simply connect it's 5V to the board. If you want to use the USB jack of the Teensy, you can connect the boards 5V to the Teensys 5V. But: Be sure to cut the little trace between Vin and VUSB/5V at the back of the Teensy. You don't want to connect the battery voltage with an USB power source.


Arduino not working / not uploading Could anybody please help me with my problem? My Arduino doesn't work correctly. I was between a project, and suddenly it started acting weird. First, it started taking about 4 minutes to compile and a minute to upload, I do not know why!

Second, now it doesn't accept any code at all. I will paste the error message below.

Also, could anything be damaged as I inserted the USB cable of the Arduino to my power bank, rated 5V 2A, for about 30 seconds as power source and then again inserted it to the computer itself.

Please help me. I have already tried searching on various forums, reinstalling the software and driver on my PC, pressing the reset button... No help so far.

  ERROR MESSAGE:
  Arduino: 1.6.7 (Windows 10), Board: "Arduino/Genuino Uno"

  avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
           Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
           Copyright (c) 2007-2009 Joerg Wunsch

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

Using Port                    : COM6
Using Programmer              : arduino
Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x49
Error opening serial port 'COM6'. (Port busy)
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x49

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Connecting to the 5v/2A power supply would cause no trouble at all. Taking 4 minutes to compile is strange but unlikely to be related to the Arduino board. "programmer is not responding" errors are communication errors.

Did the program compile without errors?
Are any LEDs lit or blinking on your board?
Is the correct board selected in the Tools | Boards menu?
Is the correct port selected in the Tools | Ports menu?
Is the correct programmer selected in the Tools | Programmer menu?
Try another USB cable.
Try pressing/releasing the board's reset button right after you click the upload button.


Is new.cpp programmed improperly? Arduino 1.8.9 I'm having trouble with my code and I'm not sure if it's a memory allocation issue. So I look at the new, delete to see if it throws errors, and finding the source code I find outrageously simple codes. So simple, I think it can't be right.

#include <stdlib.h>

void *operator new(size_t size) {
  return malloc(size);
}

void *operator new[](size_t size) {
  return malloc(size);
}

void operator delete(void * ptr) {
  free(ptr);
}

void operator delete[](void * ptr) {
  free(ptr);
}

Does this mean if I call customClass *ptr = new customClass[10]; it allocates only 10 bytes instead of sizeof(customClass)*10?

http://www.cplusplus.com/reference/new/operator%20new[]/:

  in C++, new[] is an operator with a very specific behavior: An
  expression with the new operator on an array type, first calls
  function operator new (i.e., this function) with the size of its array
  type specifier as first argument (plus any array overhead storage to
  keep track of the size, if any), and if this is successful, it then
  automatically initializes or constructs every object in the array (if
  needed). Finally, the expression evaluates as a pointer to the
  appropriate type pointing to the first element of the array.


Using TFT with hardware SPI and speaker with tone() I want to make a device with a TFT screen and a speaker that uses the builtin tone() function. However, according to the documentation, using tone() interferes with PWM on pins 3 and 11. On the Arduino Uno, the MOSI pin is default on pin 11, and it seems like defining another pin for MOSI disables hardware SPI, which, according to the module page, slows down the device. As well, the examples are written for hardware SPI and the SD card is only available with hardware SPI. What should I do here? Is there a way to redefine the default MOSI pin without disabling hardware SPI?

You are getting your wires crossed in your brain and imagining a problem where there is none.

Both PWM on pins 3 & 11, and tone(), use the Timer2 device. Only one of those can use Timer2 at a time, and they both want to use it in different ways, so there is a conflict between them.

Timer2 has nothing to do with SPI. So tone() has no effect on SPI, and nor does PWM have any effect on SPI (other than the fact that only one can come out of pin 11 at any time), since there is no internal resource conflict.


Understanding the compilation/linking/upload process (so I don't have to use the IDE) I have started to play with and arduino UNO quite recently (without any prior experience with micro-controllers). I would like to use emacs instead of the IDE, and I'd also like to know what the IDE does under the hood, in order to be able to write my own makefile. The tutorials I've found are either outdated, or are presented as a series of steps without any explanation. I'd appreciate it if someone could explain to me how the whole compliation/linking/upload process works using gcc-avr and avr-dude, and how it is used by the IDE.

If you want an exact duplication of what the IDE does but want it driven from the command line, that's what Ino is for. The full Arduino build process involves copying a lot of files from a lot of places, and is generally not trivial to duplicate.

If you're ready to let go of .ino files and the Arduino libraries, you get a much simpler toolset. avr-gcc compiles, avrdude uploads, and you're done. Here's one of my makefiles from a simple project:

CC=avr-gcc
CXX=avr-c++
CXXFLAGS=-Wall -Wextra -mmcu=atmega1284p -Os
CFLAGS=$(CXXFLAGS)
BINARY=ledmatrix
OBJECTS=

all: $(BINARY)
↹@avr-size $<

$(BINARY): $(OBJECTS)

clean:
↹@rm -f $(BINARY) $(BINARY).hex $(OBJECTS)

upload: $(BINARY).hex
↹@avrdude -c usbasp -p m1284p -U flash:w:$<:i

%.hex: %
↹@avr-objcopy -j .text -j .data -O ihex $< $@

.PHONY: all clean upload

If copying-and-pasting, be sure to replace all "↹" with tab characters.

EDIT:

I have created a repository with my buildsystem on Github.


PC  Xbee  Another Xbee Communication I have this application where I want to send commands from the PC to an Arduino, remotely, and receive an answer back.

The hardware configuration I'm using to achieve that is the following:

PC <--> Arduino with an Xbee <--> Another Arduino with another Xbee

It's just half-duplex communication. Everything seems easy, but there is a problem.

Each Arduino has an Xbee Shield with an Xbee module connected to it.
Reading the documentation of the ArduinoXbeeShield, an excerpt caught my eye:

"With the jumpers in the Xbee position (i.e. on the two pins towards theinterior of the board), the DOUT pin of the Xbee module is connected to the RX pin of the microcontroller; and DIN is connected to TX. Note that the RX and TX pins of the microcontroller are still connected to the TX and RX pins (respectively) of the FTDI chip - data sent from the microcontroller will be transmitted to the computer via USB as well as being sent wirelessly by the Xbee module. The microcontroller, however, will only be able to receive data from the Xbee module, not over USB from the computer.

With the jumpers in the USB position (i.e. on the two pins nearest the edge of the board), the DOUT pin the Xbee module is connected to the RX pin of the FTDI chip, and DIN on the Xbee module is connected to the TX pin of the FTDI chip. This means that the Xbee module can communicate directly with the computer - however, this only works if the microcontroller has been removed from the Arduino board. If the microcontroller is left in the Arduino board, it will be able to talk to the computer normally via USB, but neither the computer nor the microcontroller will be able to talk to the Xbee module."

That means I will not be able to build what I want with this configuration?
I already tried, but didn't work.

Basically with your shield you have two options:

Communicate between the MCU and the XBee at the cost of not being able to communicate between the PC and the MCU.
Communicate between the PC and the XBee at the cost of having to remove the MCU from the board completely.

Neither of which are particularly ideal.  The first option is completely out since that rules out all PC communication.  The second option turns the Arduino into just a USB->TTL Serial adapter - and a rather expensive one at that (you can get them on eBay for like $2).

What you want is to re-wire the system using jumper wires (messy, I know) so that the TX and RX pins of the XBee connect to other pins on your Uno then use SoftwareSerial to communicate with the XBee.  That will leave the Arduino's TX and RX pins free for communicating with the PC.

Alternatively invest in a different Arduino that has more hardware UART interfaces, like a Mega2560.


Fail to return int value from a function I have created myJSON library to simplify read and write values from/ to FLASH of my ESP8266 NodeMCU/ Wemos Mini.

I do not want to "mess up" the question, posting my entire code/ library - but to try to explain what happens -

I get a 0 value when reading a specific key (and not its saved value ). My assumption is that is has nothing to do with myJSON library, but my understanding in returning a value from a function.

Code is as follows:

(some explanations first):

1) json is an instance of myJSON library.

2) json.setValue(key, value) - gets a key and a value ( char/ int) and save it to FLASH.

3)json.getINTValue(key, return_var)- gets a key and return its int value to return_var. function return 1 - for successful read, and 0 when not.

inside setup()

int int_val;
// json.setValue("int_key",343); // commented out after first run - to be sure is is saved and read from flash.
Serial.println(json.getINTValue("int_key",int_val)); // NOTE 2
Serial.print("Value is: "); // NOTE 3
Serial.println(int_val);   //  NOTE 3

myJSON ( only relevant code )

bool myJSON::getINTValue (const char *key, int retval){
        StaticJsonDocument<DOC_SIZE> tempJDOC;
        myJSON::readJSON_file(tempJDOC);
        bool hasKey = tempJDOC.containsKey(key);
        if (hasKey){
          retval = tempJDOC[key];
          Serial.print("retval :"); // NOTE 1
          Serial.println(retval);  // NOTE 1
          return 1;
        }
        else {
          return 0; // when key is not present
        }
}

void myJSON::setValue(const char *key, char *value){
        StaticJsonDocument<DOC_SIZE> tempJDOC;
        myJSON::readJSON_file(tempJDOC);
        tempJDOC[key]=value;
        myJSON::saveJSON2file(tempJDOC);
}
void myJSON::setValue(const char *key, int value){
        StaticJsonDocument<DOC_SIZE> tempJDOC;
        myJSON::readJSON_file(tempJDOC);
        tempJDOC[key]=value;
        myJSON::saveJSON2file(tempJDOC);
}

result is (SEE NOTATIONS):

21:01:03.198 -> retval :343  // OUTPUT NOTE 1
21:01:03.198 -> 1            // OUTPUT NOTE 2
21:01:03.198 -> Value is: 0  // OUTPUT NOTE 3

As far a I could understand :

1) setValue works as needed ( inc. saving to flash ).
2) unexplained besides getting value = 0, is when setting a char value ( there are 2 myJSON::setValue functions to deal with int and char), code works as needed.

Appreciate any help ( and sorry for my English ).

Guy

the parameters of a function call are copied into parameters in the function. if the pointer is copied it still points to a memory where you write the data. if int is copied then changing the value changes the copy, not the variable used as parameter. reference is kind of pointer

how to make an in-out parameter by passing a parameter by reference

void setup() {

  Serial.begin(115200);
  int x = 3;
  fnc(x);
  Serial.println(x);
}

void loop() {

}

void fnc(int &x) {
  x = 5;
}

prints 5

example with a complex type

#include <IPAddress.h>

void setup() {

  Serial.begin(115200);
  IPAddress ip(192, 168, 1, 5);
  fnc(ip);
  Serial.println(ip);
}

void loop() {

}

void fnc(IPAddress& ip) {
  ip = IPAddress(192, 168, 1, 3);
}

with &ip it prints 192.168.1.3. without & it prints 192.168.1.5


Arduino Mega 2560 multiple slave via SPI I'm new to Arduino and microcontroller . I want to connect my Arduino Mega to three slaves which Arduino Unos. I know that these slaves will share MISO, MOSI, and SCK lines. However, SS is unique to each slave.

For single slave, the SS is pin 53. So, for three slaves, which other two pins can I use as SS?

Thank you for your help.

Any you like. There's nothing magic about them, as long as you have the main SS pin as an output to ensure the SPI port is in master mode.


Including Arduino library in a Makefile for Due I'm currently using a Makefile for the Arduino Due I've found on Github (with some modifications). It's useful to me cause it allows me to add a static library for cryptographic functions I need and I can't do it using the IDE. Now I need to include the WiFi library from Arduino but I don't know how. I've tried to put the path to the source (/usr/share/arduino/libraries/WiFi/src) but it gives me warnings saying that some classes are undefined. Does anyone know how to include that library?

Adding a library isn't as simple as just adding an include path.

You also have to identify each and every source file (or use wildcards as are used for the various sections of the core) and compile them into object files. It is then quite convenient to archive those into a library (.a) file which you can then link your sketch against (if you don't archive you will have to link all the objects files with your sketch in the linking phase).


How to compile Arduino ESP8266/32 on CI/CD (CLI shell cmd) platform? Like make for not ESP Arduino target, is there a CLI command like esptool.py to upload in the hardware ?

I've seen makeEspArduino but seems to be not trivial ?

What about espressif ESP32 component ?

Is Visual Micro Arduino CLI (Command Line Interface) tool mature ?

Easiest answer: Use PlatformIO. (Yes this answer is technically an advertisement, but it is the correct solution here.).

Why not the others?

makeEspArduino is dependent on GNU make, hard to make modification to, hard to get support for when something goes wrong
Visual Micro Arduino is Visual Studio extension, thus native to Windows

Why PlatformIO?

On the other hand, PIO is just a framework written in python2, runs on Windows, Mac & Linux alike and supports tons of boards and frameworks. Not only is it OS-agnostic but it also IDE agnostic. It exports project files for Eclipse, Visual Studio Code, CLion, Visual Studio, Sublime, Atom and other IDEs. The Arduino IDE will always be only a (bad) syntax highlighter.

Support boards (479 of them) range from Arduino Unos to ESP8266/ESP32 over to STM32 and nRF boards. It's also possible to compile one firmware for different environments (board), so with a well-written firmware, PIO can generate firmwares for multiple boards and frameworks alike. Frameworks include Arduino cores, ESP-IDF, STM32HAL and more.

To create a new project, you'd do

user@somefolder/$ pio init --board=nodemcuv2 --ide=vscode

To compile from CLI, you just have to execute the run target:

user@somefolder/$ pio run

To upload you'd just

user@somefolder/$ pio run -t upload

With optional --upload-port=/dev/ttyUSB0 or alike. Updating wirelessly over ArduinoOTA is also supported.

Video: https://www.youtube.com/watch?v=EIkGTwLOD7o

Documentation: http://docs.platformio.org/en/latest/