Code for 2 ultrasonic sensors This is my code:
int trigPin=13; //Sensor Trig pin connected to Arduino pin 13
int echoPin=11;  //Sensor Echo pin connected to Arduino pin 11
float pingTime;  //time for ping to travel from sensor to target and return
float targetDistance; //Distance to Target in inches
float speedOfSound=776.5; //Speed of sound in miles per hour when temp is 77 degrees.
int trigPin1=2;
int echoPin1=3;
float pingTime1;  //time for ping to travel from sensor to target and return 1
float targetDistance1; //Distance to Target in inches 1
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

  digitalWrite(trigPin, LOW); //Set trigger pin low
  delayMicroseconds(2000); //Let signal settle
  digitalWrite(trigPin, HIGH); //Set trigPin high
  delayMicroseconds(15); //Delay in high state
  digitalWrite(trigPin, LOW); //ping has now been sent
  delayMicroseconds(10); //Delay in low state
  digitalWrite(trigPin1, LOW); //Set trigger pin low
  delayMicroseconds(2000); //Let signal settle
  digitalWrite(trigPin1, HIGH); //Set trigPin high
  delayMicroseconds(15); //Delay in high state
  digitalWrite(trigPin1, LOW); //ping has now been sent
  delayMicroseconds(10); //Delay in low state

  pingTime1 = pulseIn(echoPin1, HIGH);  //pingTime is presented in microceconds
  pingTime1=pingTime1/1000000; //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
  pingTime1=pingTime1/3600; //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
  targetDistance1= speedOfSound * pingTime;  //This will be in miles, since speed of sound was miles per hour
  targetDistance1=targetDistance1/2; //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
  targetDistance1= targetDistance*63360;    //Convert miles to inches by multipling by 63360 (inches per mile)
  pingTime = pulseIn(echoPin, HIGH);  //pingTime is presented in microceconds
  pingTime=pingTime/1000000; //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
  pingTime=pingTime/3600; //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
  targetDistance= speedOfSound * pingTime;  //This will be in miles, since speed of sound was miles per hour
  targetDistance=targetDistance/2; //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
  targetDistance= targetDistance*63360;    //Convert miles to inches by multipling by 63360 (inches per mile)

  Serial.println(targetDistance);

  Serial.println(targetDistance1);

  delay(100); //delay tenth of a  second to slow things down a little.
}

Python code:
import serial #Import Serial Library

arduinoSerialData = serial.Serial('com3',9600) #Create Serial port object called arduinoSerialData

while (1==1):
    if (arduinoSerialData.inWaiting()>0):
        myData = arduinoSerialData.readline()
        myData=str(myData)
        myData= myData.replace("b'",'')
        myData=myData.replace("\\r\\n'",'')
        if myData<"3":

            print( myData)

When I compile the sketch, it shows no error.But when I run the file in python, output=0.However, when they are run individually, python gives me a valid input.so is this code correct?Also, is there a way to call for the exact c++file in python?Thanks for the help!

You are trying to measure with 2 ultrasonic sensors at once. You cannot do that so easily. You need to measure sequentially for 2 reasons:

The ultrasonic sensors might get confused by the others signal
You will miss the pulse of the one sensor, while you are reading the pulse of the other via pulseIn().

So the order of actions is like this:

Trigger sensor 1
Read sensor 1 with pulseIn()
Trigger sensor 2
Read sensor 2 with pulseIn()


Sim800L Uploading issues, HTTPACTION returns 0, 302, 701 I'm using the Sim800L module and the NEO6M GPS Module in combination with an Arduino nano to create a simple tracking device. I get the data from the GPS and try to upload it to my site with some simple PHP scripts. I'm using this code down here:

//the function - which is responsible for sending data to the web server
void sendLocation(String lat, String lon){
 Sim800l.listen();
 //The line below sets the URL we want to connect to
 Sim800l.println("AT+HTTPPARA=\"URL\", \"http://" + ipAddress +  "/log_info.php?dev_id=13&lat=" + lat + "&lon=" + lon + "\"");
 waitUntilResponse("OK");
 //GO
 Sim800l.println("AT+HTTPACTION=0");
 waitUntilResponse("200");
 Serial.println("Location sent");
 gpsPort.listen();
}

Unfortunately, when I try to use this code, in my serial monitor I get this message:

AT+HTTPACTION=0
OK
+HTTPACTION: 0,302,171
error

I Looked it up in the datasheet for the Sim800L, and the number 302 means "Found". I'm expecting the number 200 for "OK". I have no idea what I did wrong, the data is not being send to the web server for some reason. I hope you can help.
Thanks in advance!

EDIT:
The datasheet with all the errors for the Sim800L
https://www.elecrow.com/wiki/images/2/20/SIM800_Series_AT_Command_Manual_V1.09.pdf

302 is HTTP code returned by the server. It is used for redirection. Print the response with AT+HTTPREAD to see where does it redirectd.


Would rewriting my code in C help reduce RAM usage? So my program fails to run because there is not enough room for my variables as well as the Arduino Core and Stack. I can't find any more ways to optimize my program so I'm thinking about just rewriting it in C.

However, I'm not sure if that will actually help me. For example I know that in C my program will run faster because things like digitalWrite() and analogRead() have a bunch of "extras" that make it go slower, but I don't know if this will affect RAM.

So can any of the experts on here tell me if writing my code will help before I waste time doing so?

Here is my code:

#include <SoftwareSerial.h>
#include <avr/pgmspace.h>

#define FASTADC 1

// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

SoftwareSerial mySerial(0,1) PROGMEM;

byte i;

byte pixelsArray1[128];   //Array to hold the values of the individual pixles.
byte pixelsArray2[128];   //Array to hold the values of the individual pixles.
byte pixelsArray3[128];   //Array to hold the values of the individual pixles.

void setup()
{
  #if FASTADC
   // set prescale to 16
   sbi(ADCSRA,ADPS2);
   cbi(ADCSRA,ADPS1);
   cbi(ADCSRA,ADPS0);
  #endif

  pinMode(1,OUTPUT);        //Setting the 1 pin to be used for output
  pinMode(0,OUTPUT);        //Setting the 0 pin to be used for output
  pinMode(A3,INPUT);        //Input for Camera 3
  pinMode(A2,INPUT);        //Input for Camera 2
  pinMode(A1,INPUT);        //Input for Camera 1

  mySerial.begin(9600);     //Setting the data transfer rate
}

Notes:

I'm programming on the ATtiny85
I'm running Windows 10
I've never programmed in Arduino before

The simplest approach to reducing RAM usage of the program shown is to get rid of the three 128-byte pixel arrays.  They are not needed for the program to function.

Instead of writing

pixelsArray1[i]=analogRead(A1)/4;
pixelsArray2[i]=analogRead(A2)/4;
pixelsArray3[i]=analogRead(A3)/4;

write

if (analogRead(A1)/4 == 0 && analogRead(A2)/4 == 0 && analogRead(A3)/4 == 0) ++foundZero;

where foundZero is initialized to zero before the loop.  After the loop, you say something like

while (foundZero--) {
  digitalWrite(1, HIGH);
  delay(2000);
  digitalWrite(1, LOW);
  delay(2000);
}

to toggle pin 1 as many times as there were three zero pixels.

Note, the timing of the if (...) ++foundZero; statement may differ from pixel to pixel because the && evaluation may short circuit.  If the timing matters, save data in temporary variables, or check if the sum of the three is zero, etc.


Getting RFID tag data using C# I am trying to get an RFID tag number using a WinForms application. But whenever I click the Button the application stops responding. Please help regarding this.

Arduino code

void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid.init();
}

void loop() {
  if(rfid.isCard()) {
    if(rfid.readCardSerial()) {
      Serial.print(rfid.serNum[0], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[1], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[2], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[3], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[4], HEX);
      Serial.println("");
      delay(1000);
    }
  }
  rfid.halt();
}

C# code

private void button1_Click(object sender, EventArgs e) {
  try {
    serialPort1.Open();
    serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
    textBox2.Text = "connected";
    serialPort1.Close();
  }
  catch(Exception ex) {
    textBox2.Text = "Com port disconnected";
  }
}

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) {
  SerialPort sp = (SerialPort)sender;
  string indata = sp.ReadExisting();
  textBox1.Text = indata;
}

You are closing the port immediately after you open it. You need to keep it open while you are expecting data. Remove the line

serialPort1.Close();

Then, in the callback you try to access the GUI from the callback thread. That's not allowed. Use Invoke().

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
     SerialPort sp = (SerialPort)sender;
     //string indata = sp.ReadExisting();
     string indata = sp.ReadLine();
     //textBox1.Text = indata;
     Invoke(new Action<string>(
         (s) =>
         {
             textBox1.Text = s;
         }
     ), indata);
}


How can I swap a servo with a stepper motor? I'm looking for a way to swap servo 1 with a stepper motor to achieve a single direction circular motion with stops and delay. Instead, now I have the servo going back and forth to repeat the action.

This is the code I'm currently using to drive the servo:

void loop() {
  topServo.write(115);
  delay(500);

  for(int i = 115; i > 65; i--) {
    topServo.write(i);
    delay(2);
}

This is a schematic of my project:

simulate this circuit – Schematic created using CircuitLab

Can anyone help me to configure this? or point me into the right direction.
Any help would be greatly appreciated!

Firstly, I'm going to assume that you got a ULN2003 Motor driver board something like this along with your 28-BYJ48 stepper motor.

Secondly, I would always recommend using a separate power supply for your stepper motors. Even a small stepper motor like the 28-BYJ48 can draw up to 320mA, (160mA per winding).

I've used the following code to test a setup using a 28-BYJ48 stepper motor and an Arduino. The connections to the driver board (IN1 - IN4) are mapped to pins 8-11 on the Arduino in this case. The code will cause the stepper to rotate 1 full revolution in one direction, pause for 1 second and then rotate one full revolution in the other direction.

(I've often found this simple piece of code really handy for troubleshooting!)

#include <Stepper.h>

const int stepsPerRev = 2048

// initialise the stepper library on pins 8, 9, 10 & 11
Stepper myStepper(stepsPerRev, 8,10,9,11);

void setup() {
  // set the speed
  myStepper.setSpeed(4);

}

void loop() {
  // step one revolution in one direction:
  myStepper.step(stepsPerRev);
  delay(1000);

  // step one revolution in the other direction:
  myStepper.step(-stepsPerRev);
  delay(1000);

}


Garbled serial on custom arduino UNO I built my own Arduino UNO for a project at school. I think I have got the USB bootloader and Windows drivers all situated as the UNO shows up as an UNO in the device manager. When I try to load a sketch I get the error: avrdude: stk500_getsync(): not in sync: resp=0x10. (previously I received the same message with the message ending with resp=0x00)

I loaded a serial echo program using the ICSP and sent the message "serial test" to the UNO. I received this message back: {u{m}o¿wu{w

Can anyone help me troubleshoot this problem as I have ran out of things to test or look into.

Thanks in advance.

Edit: Added requested pictures of TX and RX. These were taken at Pin 0 and 1 of the headers. The scope showed the same results at the pins of the 328P but I couldn't operate the scope and hold the probe at the same time.

Sorry for the delay. I posted this question on the EE board as suggested and forgot to come back here and close this out. It was an issue with the fuses. My initial attempt to setup the 16u2 missed the step where I was supposed to change the fuses. I thought this was accomplished when loading the firmware, but was mistaken.


How can I connect an 8-relay board without using 8 digital pins? I'm looking to connect an 8-relay board to an Arduino Uno. A board like this one. However, I don't really want to use up 8 digital outputs if I don't have to. Is there some intermediate circuitry I can either buy or build that would do this?

For example, can I connect something to the serial so that sending '3' would result in binary 00000011 and thus turn on relay's 1 and 2?

Alternately, and probably more lazy, is there an extension board that would just give me a pile more digital pins?

A likely solution is to use the Arduino SPI interface and the Arduino SPI library to control a SPI relay board.  Here is a 6 year old thread talking about such a board. And another more recent relay thread where SPI is brought up.


"avrdude: stk500_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program I made an awesome program the other day, and I wanted to upload it to my Arduino. After clicking the upload button, some mean dude named avr came along and stopped me, saying:

  avrdude: stk500_getsync(): not in sync: resp=0x00

All I want to do is just upload my program, but avr won't let me. He's even unintelligible, so can someone tell me what the heck he's trying to say and how to get rid of him?

i.e.:

Whenever I try to upload a program to my Arduino, I get this error message:

  avrdude: stk500_getsync(): not in sync: resp=0x00

What does this mean, and how can I fix it?

This is caused by a generic connection error between your computer and the Arduino, and can result from many different specific problems.

Here are some easy things that can often fix this error:

Disconnect and reconnect the USB cable.
Press the reset button on the board.
Restart the Arduino IDE.
Make sure you select the right board in Tools ► Board ►, e.g. If you are using the Duemilanove 328, select that instead of Duemilanove 128. The board should say what version it is on the microchip.
Make sure you selected the right port in Tools ► Serial Port ►. One way to figure out which port it is on is by following these steps:

Disconnect the USB cable.
Go to Tools ► Serial Port ► and see which ports are listed (e.g. COM4 COM5 COM14).
Reconnect the USB cable.
Go back to Tools ► Serial Port ►, and see which port appeared that wasn't there before.

Make sure digital pins 0 and 1 do not have any parts connected, including any shields.

If none of those work, you will want to try to isolate the issue by replacing things: try a different computer on the same arduino, try a different arduino on the same computer, and try using a different USB cable.

If the issue is with the computer:

Double-check all computer-related issues in the "easy fixes" list above.
Reinstall the IDE.
Reinstall the drivers.

If the issue is with the Arduino:

Double-check all board-related issues in the "easy fixes" list above.
Make sure the microcontroller is seated correctly.
You may need to burn the bootloader.
Replace the microcontroller if you have another one handy nearby.
You may have bricked your Arduino. Sorry :(


Is it possible to use extra AVR Flash memory as non-volatile EEPROM-like Flash memory storage? In STM32 microcontrollers it is possible to use a technique that ST calls IAP, or In-Application Programming, in order to write to the Flash memory from your running application. They even have a nice Application Note (ex: AN2594) to describe a really ingenious way to use two Flash memory pages to emulate EEPROM while using "wear-leveling" to reduce Flash memory wear during erase cycles.

I have wondered for years: can AVR do this? Ex: the ATmega328 mcu in the Arduino Uno, Nano, etc--can you write code to store data from your application into Flash memory, thereby increasing non-volatile storage space for data acquisition for instance?

If so, can you please point me to some resources or examples, including example code, reference manuals or datasheets, etc, that might help me implement this? I've done some looking in the datasheet and haven't found anything so far but maybe I'm just not looking hard enough or know well enough what I'm looking for.

Yes you can. This Arduino IDE add on lets you make calls to code store in the bootload of memory so you can make changes to the flash memory.
https://majek.sh/en/writing-to-internal-flash-on-arduino/

The number of times you rewrite a cell are limited.
I'd suggest you are better off with adding a FRAM memory chip.
Get a 5V part with SPI interface. Fast reads, virtually unlimitless writes (trillions)
https://www.digikey.com/products/en/integrated-circuits-ics/memory/774?k=fram+memory&k=&pkeyword=fram+memory&pv276=15&FV=ffe00306%2C1f140000%2C1fec000b&quantity=0&ColumnSort=0&page=1&stock=1&pageSize=25


Duemilanove serial TX/RX: which is what? I want to use the GSM shield. For my project, I will hook it up directly to pins 0 and 1 (TX/RX). Will it work right away? Do I have to know which is TX and which RX and declare it?

I will not be using SoftwareSerial.

I will not be using SoftwareSerial

That means you'll use the standard Serial() library.

  Do I have to[...] declare it?

Not if you use the standard Serial.begin() instruction. The Duemilanove uses pins 0/1 automatically for TX/RX

  Do I have to know which is TX and which RX?

Kinda... you have to know which one is which so you wire it correctly. The TX of the board should go to the RX of the GSM shield, and vice versa. Pin 0 is RX and 1 is TX.


strcat char concatenation trouble Still don't understand about char concatenation.

void setup() {

  testCounter(3);

}

void loop() {
  // put your main code here, to run repeatedly:
}

char testCounter(int countx){
  char a[10];
  strcpy(a, "COUNTER: ");
  strcat(a, printDigits(countx));
  return a;
}

char printDigits(int digits){
  char a[3];
  if(digits < 10) {
    strcpy(a, "0");
    sprintf(a,"%d",digits);
  } else {
    sprintf(a,"%d",digits);
  }
  return a;
}

Error:  invalid conversion from 'char' to 'const char' [-fpermissive]* in testCounter line:

strcat(a, printDigits(countx));

Don't understand this part of error.

printDigits function return char, so... strcat should be work. But why still error?

Please help...

char printDigits(int digits){

You are telling the compiler you will return one character.

 char a[3];

a is three characters. Thus the declaration doesn't match.

You could change the declaration to:

char * printDigits(int digits){

But even that would be bad because a would go out of scope after the function returns.

 char a[3];

That's a little short for putting an integer into. An integer might be 5 characters, plus possibly a minus sign, and you need a trailing "null" at the end. Seven bytes would be safer.

The simplest way of doing what you seem to be wanting is:

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

void loop() {
}

char testCounter(int countx){
  char a[15];
  sprintf (a, "COUNTER: %02d", countx);
  Serial.println (a);
}

Also, here:

  if(digits < 10) {
    strcpy(a, "0");
    sprintf(a,"%d",digits);
  } else {

That won't work because you are putting "0" into a and then overwriting it with sprintf.

  printDigits function return char, so... strcat should be work. But why still error?

Look at the prototype for strcat:

http://www.cplusplus.com/reference/cstring/strcat/

It expects char * not char. They are different things. One is a pointer, one isn't.


Arduino serial informations Is it possible to change serial information of arduinos board ?
For example I have an arduino uno with this serial informations :

{
      comName: '/dev/cu.usbmodem1411',
      manufacturer: 'Arduino (www.arduino.cc)',
      serialNumber: '75430333137351804230',
      pnpId: '',
      locationId: '0x14100000',
      vendorId: '0x2341',
      productId: '0x0043'
}

I want to modify for example the manufacturer to be able to automatically detect the device whatever the comName is. I don't want to detect arduino board I want to detect arduino board modify by me without make a serial connection.

Once you have purchased a USB vendor ID you can edit the firmware within the Arduino installation at hardware/arduino/firmwares/atmegaxxu2/arduino-usbserial/ with your vendor ID, chosen product ID, and other USB parameters as you wish and then rebuild the firmware and upload it to the ATmega16U2 on the board via ISP.

If you do not wish to purchase a vendor ID for the time being then you can use 0x6666, the prototype vendor ID, in the meantime, but you are not allowed to make products using that vendor ID available to the public.


Having an issue accessing values from a pointer Context

This may be more of a C++ question than an arduino specific question, but it's dealing with arduino c++ so I thought I'd start here.

I'm building a class to abstract some simple melody playing that I want for a project. I got everything working in a procedural way, so I started moving everything out to a header and cpp file (still new-ish territory for me).

The general concept is that I want to call a public method on my class to allow my code to play a specific melody. I defined an enum for each melody available and in my playMelody() method I'm using a couple of pointers and a switch statement to get the specific frequencies and durations I need to play the specific melody. These frequency and duration values are stored in private arrays in the class.

Here's the header:

// MelodyPlayer.h

enum MELODY
{
    SHAVE_AND_A_HAIRCUT = 0,
    IDLE,
    READY,
    PROCESSING,
    COMPLETE,
};

class MelodyPlayer
{
    uint8_t speakerPin;

    int melody_shaveAndAHairCut[9];
    int durations_shaveAndAHairCut[9];
    int *activeMelody;
    int *activeDurations;

    void _playMelody();

public:
    MelodyPlayer(uint8_t speakerPin);
    void playMelody(MELODY name);
};

MelodyPlayer::MelodyPlayer(uint8_t pin)
{
    speakerPin = pin;

    int melody_shaveAndAHairCut[] = {
        NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4, 0};

    int durations_shaveAndAHairCut[] = {
        4, 8, 8, 4, 4, 4, 4, 4, 4};
}

void MelodyPlayer::playMelody(MELODY name)
{
    switch (name)
    {
    case SHAVE_AND_A_HAIRCUT:
        Serial.println("Shave and a hair cut");
        activeMelody = melody_shaveAndAHairCut;
        activeDurations = durations_shaveAndAHairCut;
        break;
    }

    _playMelody();
}

And here's the implementation:

// MelodyPlayer.cpp

void MelodyPlayer::_playMelody()
{
    Serial.println("Playing Melody");
    // * pulled from the toneMelody arduino example
    for (int thisNote = 0; thisNote < 8; thisNote++)
    {

        int activeDuration = activeDurations[thisNote];
        int noteDuration = 1000 / activeDurations[thisNote];
        int noteFrequency = activeMelody[thisNote];

        Serial.println(thisNote);
        Serial.println(activeDuration);
        Serial.println(noteDuration);
        Serial.println(noteFrequency);

        tone(speakerPin, noteFrequency, noteDuration);

        int pauseBetweenNotes = noteDuration * 1.30;
        delay(pauseBetweenNotes);

        noTone(speakerPin);
    }
}

And I call it in my .ino file like this:

MelodyPlayer player = MelodyPlayer(SPEAKER);
player.playMelody(SHAVE_AND_A_HAIR_CUT);

The problem

I'll upload the sketch and everything fires. The problem I'm running into is that when I get to the private _playMelody() method the values I get for activeDuration, noteDuration and noteFrequency are all ultra wrong:

I imagine I'm doing something wrong with the setting and getting of the values via the pointer variable I set in the switch statement, but I'm not sure where I'm going wrong.

You can see/pull down the actual code from the abstracting-to-class branch of my repo if you want to dig in.

I've done a similar dynamic-selection-via-pointer in a proof of concept before, but it was procedurally written, not classed. I can't seem to figure out where the difference is :|

Any ideas?

As Majenko mentioned in the comment, you created new local arrays in the constructor, but never put anything in the member arrays of the classes. They have the same name, but are not the same variable. Responsible for creating the new variable is the keyword int. However, you cannot simply assign array values by just omitting the int. Therer are multiple possibilities:

You can fill the array for each index: durations_shaveAndAHairCut[0] = 1;
You can copy your local array to the member variable with memcpy: memcpy((void*)this->durations_shaveAndAHairCut, (void*)durations_shaveAndAHairCut, 9*sizeof(int));
You can declare the arrays static in the class declaration and initialize it outside of the constructor in MelodyPlayer.cpp:

int MelodyPlayer::durations_shaveAndAHairCut[] = {
    4, 8, 8, 4, 4, 4, 4, 4, 4};

I prefer the last option.


Arduino zero Error: unable to find CMSIS-DAP device I am uploading a test sketch(Blink) to my new Zero(with Wifi101 shield) and when I press Upload in the IDE, the Console says the following:

Arduino: 1.6.10 (Linux), Board: "Arduino/Genuino Zero (Programming Port)"

Open On-Chip Debugger 0.9.0-gd4b7679 (2014-10-03-00:26)
Licensed under GNU GPL v2
For bug reports, read
    http://openocd.org/doc/doxygen/bugs.html
debug_level: 0
adapter speed: 500 kHz
adapter_nsrst_delay: 100
cortex_m reset_config sysresetreq
Error: unable to find CMSIS-DAP device
Error: No Valid JTAG Interface Configured.
Error: No Valid JTAG Interface Configured.

I am using the Zero programming port.

I had exactly the same error with the same board. Running the IDE as root solved the problem. So, Chris was right pointing out a permission issue.
I found more information here : http://bitofahack.com/post/1437909576
Then I added the file /etc/udev/rules.d/98-openocd.rules :
ACTION!="add|change", GOTO="openocd_rules_end"
SUBSYSTEM!="usb|tty|hidraw", GOTO="openocd_rules_end"
ATTRS{product}=="*CMSIS-DAP*", MODE="664", GROUP="plugdev"
LABEL="openocd_rules_end"

I then ensured that I was member of group plugdev.
udev looks for changes in his rules directory so you don't have
to restart it.
I plugged the board again and it worked.
Note that you can force udev to read the rule files again by entering :
sudo udevadm control --reload

I had to do this because I first made a mistake in the rule file.
Hope this helps.


Arduino mini requires uploading on every power up? My Arduino mini is experiencing some really strange problem.

I'm using the BlinkWithoutDelay example sketch for testing:

const int ledPin =  13;
int ledState = LOW;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated
long interval = 1000;           // interval at which to blink (milliseconds)

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

void loop()
{
    unsigned long currentMillis = millis();

    if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
        ledState = HIGH;
    else
        ledState = LOW;

   // set the LED with the ledState of the variable:
   digitalWrite(ledPin, ledState);
  }
}

The program basically turns pin 13 on and off every 1000ms.

When I uploaded this sketch into the mini (via Arduino Uno board, sans Atmega chip), the scope reading of pin 13 shows nice square waves (1s pulsewidth, 2s period), as expected.

I then unplug the USB cable powering the mini through the Uno board, wait for a few seconds for the scope traces to settle (I only have an old analog one at hand), and then plug it back in to turn on the board. However, the pin output is different - I now get a train of three pulses (60ms wide, 60ms between pulses) at sporadic intervals.

Uploading the sketch then yields the desired square waves again.

What is going on here? I'm fairly sure the mini has nonvolatile memory and it's intact (otherwise the bootloader through which I upload the sketch would not work).

There was a defective bootloader that shipped on some Arduino devices which caused the symptom you describe. See:

http://forum.arduino.cc/index.php?topic=51172.0

http://forum.arduino.cc/index.php?topic=74090.0

If that's the case, your options are to re-write the bootloader yourself (if you have the capability) or return to the manufacturer.


Aduino 7 segment dice project I am struggling with the code that I should write for my project. I finished my breadboard but I have never learnt programming before so I cannot write the program for the dice.
My project is to make the dice output random numbers when the button is pressed.
This is what I have completed already. I just want to know how to complete the program to make it work for my arduino.

This is the code so far:

int leda = 2;
int ledb = 3;
int ledc = 4;
int ledd = 5;
int lede = 6;
int ledf = 7;
int ledg = 8;
int ledh = 9;
int leda1 = A0;
int ledb1 = A1;
int ledc1 = A2;
int ledd1 = A3;
int lede1 = A4;
int ledf1 = A5;
int ledg1 = A6;
int ledh1 = A7;

void setup()
{
    Serial.begin(9600);
    pinMode(leda, OUTPUT);
    pinMode(ledb, OUTPUT);
    pinMode(ledc, OUTPUT);
    pinMode(ledd, OUTPUT);
    pinMode(lede, OUTPUT);
    pinMode(ledf, OUTPUT);
    pinMode(ledg, OUTPUT);
    pinMode(ledh, OUTPUT);
    pinMode(leda1, OUTPUT);
    pinMode(ledb1, OUTPUT);
    pinMode(ledc1, OUTPUT);
    pinMode(ledd1, OUTPUT);
    pinMode(lede1, OUTPUT);
    pinMode(ledf1, OUTPUT);
    pinMode(ledg1, OUTPUT);
    pinMode(ledh1, OUTPUT);

    pinMode(12, INPUT);

    digitalWrite(12, HIGH);
}

if (number == 1)
{
    digitalWrite(2, HIGH);
    digitalWrite(7, HIGH);
}

else if (number == 2)
{
    digitalWrite(3, HIGH);
    digitalWrite(2, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(9, HIGH);
    digitalWrite(8, HIGH);
    delay(200);
}
else if (number == 3)
{
    digitalWrite(3,HIGH);
    digitalWrite(2,HIGH);
    digitalWrite(5,HIGH);
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    delay(200);
}

else if (number == 4)
{
    // do number 4
}

else if (number == 5)
{
    // do number 5
}

// ... etc
// Additional 'numbers' have been removed for brevity

About random numbers

What you are trying to achieve is actually not that easy. An Arduino is
basically a computer, and as any computer, it is designed to execute
instructions in a very deterministic fashion. Computers are not good
at randomness and, unless fitted with dedicated hardware, they cannot
generate random numbers. Given this, you are left with two options:

pseudo-random number generators
entropy gathering

The first is the easiest:

int first_dice  = random(1, 7);  // 1 (inclusive) to 7 (exclusive)
int second_dice = random(1, 7);

and voilà! You have two random-looking numbers. They are random-looking
in the sense that you will find no obvious pattern in any sequence of
numbers you draw. However, if you reset your Arduino, either with the
reset button or by power-cycling it, it will give you the exact same
sequence as in the first run. Thus, pseudo-randomness in useless unless
you commit to never unpower your circuit. It is a good starting point,
however, if your main goal is to get started with Arduino programming.

Entropy gathering means getting some randomness from outside the
Arduino: you would connect it to some source of randomness and perform
some measurement that has unpredictable outcome. A human being is a good
source of randomness: if you require the user to press a button before
displaying the dice value, the timing of the button press is a good
random source. The micros() function can be used to get the current
time with 4 µs resolution, which is more than enough for this
purpose. Entropy gathering is usually used in tandem with pseudo-random
number generators, as a way to seed them, like this:

wait_for_the_user_to_press_a_button();
randomSeed(micros());
int first_dice =  random(1, 7);
int second_dice = random(1, 7);

If you cannot have human interaction, you could try to get some
electromagnetic noise by performing an analogRead() on a floating pin.
Ideally you would connect that pin to an analog noise source. See the
first comment to this answer for more information on this option.

About arrays and loops

You should definitely try to find a good tutorial about arrays and
loops. Whenever you find yourself writing tons of almost-identical lines
of code, you should wonder whether you can replace that repetition with
a loop. For example, for displaying the digit 1, you may write:

if (number == 1) {
    digitalWrite(leda,  LOW);
    digitalWrite(ledb, HIGH);
    digitalWrite(ledc, HIGH);
    digitalWrite(ledd,  LOW);
    digitalWrite(lede,  LOW);
    digitalWrite(ledf,  LOW);
    digitalWrite(ledg,  LOW);
}

(I am using the "canonical" A–G letter assignments, and yes, you should
also take care of setting to LOW the segments you want to be off).
This code is an obvious candidate for being replaced by a loop:

if (number == 1) {
    for (int segment = 0; segment < 7; segment++)
        digitalWrite(leds[segment], digit1[segment]);
}

This requires that you first define the following arrays:

//                A     B     C     D     E     F     G
int leds[]   = {  2,    3,    4,    5,    6,    7,    8 };
int digit1[] = { LOW, HIGH, HIGH,  LOW,  LOW,  LOW,  LOW};

This logic can be pushed one level further by using a two-dimensional
array (an array of arrays): instead of defining six arrays digit1,
digit2... digit6, you create an array of arrays like this:

int digits[][7] = {
         /*          A     B     C     D     E     F     G  */
         /* 1 */  { LOW, HIGH, HIGH,  LOW,  LOW,  LOW,  LOW},
         /* 2 */  {HIGH, HIGH,  LOW, HIGH, HIGH,  LOW, HIGH},
         ...
};

and you use digits[number] instead of digit1, etc. This way you get
rid of the whole if () ... else if () chain, replaced by:

for (int segment = 0; segment < 7; segment++)
    digitalWrite(leds[segment], digits[number-1][segment]);

Take care though that in C++ arrays are indexed from zero, which is why
you need to use number-1 as the index in digits. If you have more
than one die (which is your case), you can also put their pin
assignments in a two-dimensional array. Then all the dice updating code
would be wrapped inside a loop indexed by the die number. Putting all
this together you end up with something like this:

// Pin assignments.
int leds[][7] = {
   /*                A     B     C     D     E     F     G  */
   /* 1st die */  {  2,    3,    4,    5,    6,    7,    8 },
   /* 2nd die */  { A0,   A1,   A2,   A3,   A4,   A5,   A6 }
};

// 7-segment "font".
int digits[][7] = {
         /*          A     B     C     D     E     F     G  */
         /* 1 */  { LOW, HIGH, HIGH,  LOW,  LOW,  LOW,  LOW},
         /* 2 */  {HIGH, HIGH,  LOW, HIGH, HIGH,  LOW, HIGH},
         /* 3 */  {HIGH, HIGH, HIGH, HIGH,  LOW,  LOW, HIGH},
         /* 4 */  { LOW, HIGH, HIGH,  LOW,  LOW, HIGH, HIGH},
         /* 5 */  {HIGH,  LOW, HIGH, HIGH,  LOW, HIGH, HIGH},
         /* 6 */  {HIGH,  LOW, HIGH, HIGH, HIGH, HIGH, HIGH}
};

void setup()
{
    for (int die = 0; die < 2; die++) {
        for (int segment = 0; segment < 7; segment++) {
            pinMode(leds[die][segment], OUTPUT);
        }
    }
}

void loop() {
    for (int die = 0; die < 2; die++) {
        int number = random(1, 7);
        for (int segment = 0; segment < 7; segment++)
            digitalWrite(leds[die][segment], digits[number][segment]);
    }
    delay(200);
}

This is still lacking the entropy gathering phase discussed above.


Simultanous read and read/write on two serial connections At the moment I'm using two softserials to connect to a GPS and an GSM module.

It seems not possible to have two open software-serials. So I was looking for an solution

After the initial-setup, the GPS module is only needed to be read from; while the GSM module needs to be bidirectional. So:

GPS > listen only
GSM > listen and write

Now I came across the GPS library from Adafruit, which uses an interrupt to receive data. Is this instead of a software serial. Or do I again run into the limitation?

An other solution might be to use the D0 and D1 to attach eg the GPS module. But than I won't be able to see the debug messages in my serial monitor. Is that correct?

Sorry in advance for these n00b questions. But I'm frustrated the things dont work as I want :)

edit

This is the adafruit GPS board.
And the board with whom it is connected: Gboard
The Sim900 is connected to D2/D3 and the GPS is connected to A2/A3.
D0/D1 are connected to a FTDI breakout board, which is plugged into my USB.

Adafruit_GPS.h (line 132-), which is included in Adafruit_GPS.cpp (line 13) refers in turn to the SoftwareSerial library on AVR platform and Arduino IDE version > 100.

#ifdef __AVR__
#if ARDUINO >= 100
    SoftwareSerial *gpsSwSerial;
#else
    NewSoftSerial *gpsSwSerial;
#endif
#endif

This means it uses software serial on an Uno. It also means if your problem is indeed with Software Serial, that is the library to check for bugs / updates or commit a patch to.


LSB/MSB and shiftOut Here is the shiftOut function code from wiring_shift.c

void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
     uint8_t i;

     for (i = 0; i < 8; i++)  {
           if (bitOrder == LSBFIRST)
                 digitalWrite(dataPin, !!(val & (1 << i)));
           else
                 digitalWrite(dataPin, !!(val & (1 << (7 - i))));

           digitalWrite(clockPin, HIGH);
           digitalWrite(clockPin, LOW);
     }
}

Does this mean that least significant bit is on the left and most significant bit is on the right? Or LSBFIRST means that will be the last outputted bit so it will be "first" in outputted sequence?

One more thing

here is a sample code:

shiftOut(dataPin, clockPin, LSBFIRST, B00101001);
shiftOut(dataPin, clockPin, LSBFIRST, B11010011);

Why does this

union
{
     word uniform;
     byte separate[2];
} state;

state.uniform = 54057; // aka 11010011 00101001
shiftOut(dataPin, clockPin, LSBFIRST, state.separate[1]);
shiftOut(dataPin, clockPin, LSBFIRST, state.separate[0]);

have different output but if i swap last two lines it works correctly?

Integer values of the Arduino have the MSB left and the LSB right. The shiftOut() function let's you choose, how the order should be timewise. If you provide LSBFIRST, the function will start the transmit with the LSB (on the right) and then go left to the MSB. Otherwise it will start with the MSB and then go right to the LSB. So this effects only the time order of the bits, in that they get transmitted.


why leonardo bootloader is bigger than UNO? Apparently leonardo and UNO are very similar boards.

However, despite that both have the same flash memory size, Leonardo bootloader is considerably bigger than UNO bootloader (4KB vs 0.5KB).

what would be the reason? it is there any way to use smaller bootloader in leonardo?

Uno specs: https://www.arduino.cc/en/Main/ArduinoBoardUno

Leonardo specs: https://www.arduino.cc/en/Main/ArduinoBoardLeonardo

Thanks!

Apparently leonardo and UNO are very similar boards.

No, they are very, very different.

The Uno uses an external USB-UART bridge. This means that the bootloader code only has to read from the UART in order to program the device.

The Leonardo has USB support built into the MCU. This means that the bootloader must contain an entire USB Device stack in order to process the USB packets and then pass the payload to the programming routines.


SPI Slave Programming for Arduino In my application Arduino Due is configured as master and instead of the actual slave device I am making use of Arduino Uno as Slave.I will share the Master code which I have worked out. Can Anyone please help me with respect to slave code of Arduino Uno to display the data in serial monitor at slave side. Any Help With respect to this aspect will be greatly greatly appreciated.
#include <SPI.h>

SPISettings mySettting(125000, MSBFIRST, SPI_MODE0);
const uint8_t ss = 10;

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

  SPI.begin();

  digitalWrite(ss, LOW);
  SPI.beginTransaction(mySettting);
  SPI.transfer(0x00);
  SPI.transfer(0x25);
  SPI.transfer(0x1C);
  SPI.endTransaction();
  digitalWrite(ss, HIGH);
}

void loop() {
}

Thanks for the reply.
Referring to the code attached below at the slave side as you have mentioned that HEX to be displayed in serial monitor window, Do I need to add the HEX at the master side I mean Do I need to load the Hexadecimal data (0x00251C) into HEX buffer??
Thanks in Advance
#include <SPI.h>

SPISettings mySettting(125000, MSBFIRST, SPI_MODE0);
const uint8_t ss = 10;

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

  SPI.begin();

  digitalWrite(ss, LOW);
  SPI.beginTransaction(mySettting);
  SPI.transfer(0x00);
  SPI.transfer(0x25);
  SPI.transfer(0x1C);
  SPI.endTransaction();
  digitalWrite(ss, HIGH);
}

void loop() {
}

SPI.h library by default only support Master mode, the SPI.begin() will automatically set slave select (ss) pin to HIGH whether you have pinMode(ss, OUTPUT) in your setup() code or not and set the Arduino as an SPI master. This can be see on SPI library source code.
As the SPI library does not contain the functionality for slave mode, in order to use Arduino as a Slave, you will need to do some customised setup, mainly on 1) setting MISO as OUTPUT for slave to send data; 2) enable slave mode by setting the SPCR register; 3) enable interrupt when data is received. Here is an example for an SPI slave on Arduino.
#include<SPI.h>

volatile boolean received;
volatile byte receivedData;

ISR (SPI_STC_vect)        //Inerrrput routine function
{
  receivedData = SPDR;   // Get the received data from SPDR register
  received = true;       // Sets received as True
}

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

  pinMode(MISO,OUTPUT);   //Sets MISO as OUTPUT
  SPCR |= _BV(SPE);       //Turn on SPI in Slave Mode
  received = false;
  SPI.attachInterrupt();  //Activate SPI Interuupt
}

void loop()
{
  if(received) {
    SPDR = receivedData;    // send back the received data, this is not necessary, only for demo purpose
    received = false;
    Serial.print(receivedData, HEX);
  }
}


Hold a random number I am trying to create a code that has at least 6 servos attached and two buttons for a two player game. I want to be able to roll a random number and have it hold that value then when it is that players turn. The program should also take that previous number and add it to the next. It would eventually be adding up all the values of the rolls. This is what I have so far. Any advice would be helpful. Thanks!

#include <Servo.h>

Servo myservo;

int pos = 0;    // variable to store the servo position
int x;
int button = 8;
int BUTTON;
int randomNumber;
int xPrevious;

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

void loop() {
  for (x = 2; x <= 7; x += 1) {
    myservo.attach(x);

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

      BUTTON = digitalRead(button);
      if(BUTTON == LOW){
        randomNumber = random(1,7);
        delay(350);
        Serial.println(randomNumber);
      }
    }
    randomNumber += xPrevious;
  }
}

You are redefining the random number wrongly each time with

randomNumber += xPrevious;

this is an error. You need another new variable (initialised at 0) to keep the running totals of all the random "rolls". You should be able to fix your program now you know this. Maybe something like

TotalofTherandomNumbers += xPrevious;

to start off with.

You may also want to add in the after the line

 randomNumber = random(1,7);

a new function, of yours, that takes random value randomNumber  do the action in the game, what ever that is,  depending on if its the first or second player.


Error in IR receiver project I'm trying to receive remote information with an IR receiver and this is my code:

#include <IRremote.h>

int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
  delay(100);
}

I tried to upload this to Arduino and it says:

exit status 1
redefinition of 'int RECV_PIN'

How can I fix this?

Apparently the name RECV_PIN is used somewhere else, presumably in IRRemote.h -- although not in any version of it I can find.  Anyway, just change the name of RECV_PIN to something which doesn't conflict.

For example:

int MY_RECV_PIN = 11;
IRrecv irrecv(MY_RECV_PIN);


Why does this not put my Arduino Mega to sleep? I have the following program which is supposed to print the words "Program is on" once and then go to sleep. However it doesn't go to sleep and continues to print "Program is on" over and over again.

#include <avr/sleep.h>

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

void loop()
{
  Serial.println("Program is on");
  sleepNow();
}

void sleepNow()
{
  // Choose our preferred sleep mode:
  set_sleep_mode(SLEEP_MODE_IDLE);
  // Set sleep enable (SE) bit:
  sleep_enable();
  // Put the device to sleep:
  sleep_mode();
  // Upon waking up, sketch continues from this point.
  sleep_disable();
}

In idle sleep, the timer interrupts will wake the processor, as  Ignacio Vazquez-Abrams said in his comment.

A "higher" sleep mode works, however I had to add Serial.flush () otherwise it only printed "P" because the processor goes to sleep before the serial output buffer has been emptied.

#include <avr/sleep.h>

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

void loop()
{
  Serial.println("Program is on");
  Serial.flush ();
  sleepNow();
}

void sleepNow()
{
  // Choose our preferred sleep mode:
  set_sleep_mode(SLEEP_MODE_PWR_SAVE);
  // Set sleep enable (SE) bit:
  sleep_enable();
  // Put the device to sleep:
  sleep_mode();
  // Upon waking up, sketch continues from this point.
  sleep_disable();
}

See my page about power savings.


Understanding ArduinoJson capacity calculation assistant I am trying to figure out how ArduinoJson capacity can be calculated, therefore I came by the Assistant web application developed by the developer of the library https://arduinojson.org/v6/assistant/
Here what I do not understand is, why when I use either of the following two JSON strings, the helper shows me the same capacity? I would expect that the longer JSON values will result in a bigger capacity, but this does not seem to be the case.
{
  "wifi": {
    "ssid": "S",
    "password": "P",
    "hostname": "H"
  },
  "administration": {
    "username": "U",
    "password": "P"
  }
}

{
  "wifi": {
    "ssid": "SSSSSSSSSSSSSSSSSSSSSSSSSSS",
    "password": "PPPPPPPPPPPPPPPPPPPPPPPPPP",
    "hostname": "HHHHHHHHHHHHHHHHHHHHHHHHHHHH"
  },
  "administration": {
    "username": "UUUUUUUUUUUUUUUUUUUUUUUUUUUUUU",
    "password": "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP"
  }
}

I am trying to calculate the capacity using the assistant using the following configuration:
ESP8266 / Deserialize / char*
Could you anyone explain this to me? Apparently I understand the "reason" behind the capacity wrong?

If you look at the details of the numbers reported, you should see:
Data structures     112
Strings             0
Total (minimum)     112
Total (recommended) 128

As you see, there are exactly zero bytes allocated for the strings. This
means that the library does not copy the strings, and instead references
them from the character array you provide as an input.
If you instead configure the library for Stream input, it will have to
store the strings, and the capacity is then very different for these two
documents.


Reading values with HC-05 and sending commands at the same time working inconsistently Not good at coding at all, so I'm at a total loss here.

But I'm doing a project that involves controlling a larger DC voltage through a mosfet.
What I'm doing is I'm using a HC-05 to transmit data between a phone and the Arduino Uno. Seeing the value within a couple of seconds is necessary.

However, sending the mosfet gate a command to open or close up work very inconsistently. Sometimes never and sometimes it takes up to 30 seconds for it to register.

The code here is a short version of the project that I'm working on, but behaves similarly.

#define mosfet 11
int state = 0;
int gate = 0;
int maxgate = 255;
int mingate = 0;

void setup() {
  delay(2000);
  pinMode(mosfet, gate);
  analogWrite(mosfet, 0);   //starts closed
  Serial.begin(9600);
}

void loop() {
  while(Serial.available() > 0){
    state = Serial.read();

    for (int y=0; y <= 5; y+=5){
      delay(500);
      Serial.println("testphase 1");
      delay(500);
    }

    for (int y=5; y >= 0; y--){
      delay(250);
      Serial.println("testphase 2");
      delay(250);
    }

    if (state == '0') {
    gate = gate + 1;
    if(gate > maxgate) gate = maxgate;
    analogWrite(mosfet, gate);
    Serial.println(int(gate));Serial.print(", +1");
    state = 0;
    }

  if (state == '1') {
    gate = gate + 10;
    if(gate > maxgate) gate = maxgate;
    analogWrite(mosfet, gate);
    Serial.println(int(gate));Serial.print(", +10");
    state = 0;
    }
}
}

When sending 'State == 1', for example it will go through both for loops multiple times and the maybe sometimes do gate + 10. Sometimes the commands goes completely ignored.

I have no idea how I would interrupt a loop to execute the given command and then go back.

Actually got it working myself, but thank you so much for your help @chrisl

Ditched the for loop completely just to try things out and reorganized my code a bit. Surprisingly it started to work well enough.

Basically just moved my measuring stuff outside the while loop*(and now that I think about it, why would it ever be withing the while loop? Literally makes no sense)* and to the end of the whole void loop part, and only polled for state changes within the while loop while the BT connection was active.

Doesn't miss a command as far as I can tell, and the adjustment is within 2 seconds when using my whole code, which is perfect. Also the whole program doesn't just freeze itself while trying to think what happened when the change set was send.

Here's a short version, should somebody bump into this thread in the future.

void loop() {
   while(Serial.available() > 0){
    state = Serial.read();

  if (state == '0') {stuff happens here,
    }
    }  //End of the while loop.

  sensors.requestTemperatures();
  delay(1000);
  Celcius=sensors.getTempCByIndex(0);
}


Teensy 4.1 serial communication with 7N2 (7 databits no parity 2 stopbits) I have ported a project from arduino Due to a teensy 4.1
In the project I read data from a sensor which speaks serial at 7 databits, no parity and 2 stopbits (no configurable).
Now it seems that teensy does not support this dataformat.
Could I read my sensor in a way using teensy 4.1? I could maybe use softwareserial but the format does not seem to be configurable.

There is no difference between 7N2 and 8N1. You just have the most significant bit of your data value being the first of the two stop bits.
To transmit just set the most significant bit to 1.
To receive just ignore the most significant bit.
For example:
Serial.write(val | 0x80);

And:
uint8_t val = Serial.read() & 0x7F;


using a variable to index an array I'm using the keypad library to return a number 1-9. (im fairly sure this returns an int)
I have an array (data) showing the state of each button press.
so i would like the number returned by the keypad (key) to be the index number that gets edited from 0 to 1 and from 1 to 0.
    //REMOTE KEYPAD TO CONTROL OUTPUTS OVER SERIAL

#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},

};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

int iAm = 1;                                    //this is device number 1
float checkSum = 0.00;                          //check sum to send as serial
float voltage = 5.26;                           //system voltage
bool data[8] {0, 0, 0, 0, 0, 0, 0, 0, 0};       //keypad output call

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

void loop() {

  int key = keypad.getKey();

  if (key) {
        data[key] = 1;

    //checkSum = voltage * (iAm + data[0] + data[1] + data[2] + data[3] + data[4] + data[5] + data[6] + data[7] + data[8] + data[9]);
    //Serial.print(iAm);
    //Serial.print("/");
    Serial.print(data[1]);
    Serial.print("/");
    Serial.print(data[2]);
    Serial.print("/");
    Serial.print(data[3]);
    Serial.print("/");
    Serial.print(data[4]);
    Serial.print("/");
    Serial.print(data[5]);
    Serial.print("/");
    Serial.print(data[6]);
    Serial.print("/");
    Serial.print(data[7]);
    Serial.print("/");
    Serial.print(data[8]);
    Serial.print("/");
    Serial.print(data[9]);
    Serial.print("/");
    Serial.print(voltage);
    Serial.println("/");
    //Serial.println(checkSum);

  }

}

i can edit the index location by typing data[1] = 1 but not as a variable so i suspect an index cant be addressed as int? but i don't know what it should be addressed as or how to change it to that.

not going to pretend i understand why all my keypad numbers are 48 higher than the number printed on the keypad but:
int key2 = key -48;

works


Confusion on array definition at Arduino website See the below explanation about Arrays from Arduino's official site:

  Creating (Declaring) an Array

  All of the methods below are valid ways to create (declare) an array.

  int myInts[6];
  int myPins[] = {2, 4, 8, 3, 6};
  int mySensVals[6] = {2, 4, -8, 3, 2};
  char message[6] = "hello";

  You can declare an array without initializing it as in myInts.

  In myPins we declare an array without explicitly choosing a size. The
  compiler counts the elements and creates an array of the appropriate
  size.

  Finally you can both initialize and size your array, as in mySensVals.
  Note that when declaring an array of type char, one more element than
  your initialization is required, to hold the required null character.

I have the following problems to understand:

Isn't int mySensVals[6] = {2, 4, -8, 3, 2}; wrong? I count 5 elements.
Isn't char message[6] = "hello"; is wrong as well? I count 5 elements.

1-) Isn't int mySensVals[6] = {2, 4, -8, 3, 2}; wrong? I count 5 elements.

No, not wrong at all. There are 6 elements (as the definition says), and the first five are set to 2, 4, -8, 3 and 2. The sixth is undefined.

  2-) Isn't char message[6] = "hello"; is wrong as well? I count 5 elements.

No. There are 6 there. To quote your quote:

  Note that when declaring an array of type char, one more element than your initialization is required, to hold the required null character.

So "hello" is actually "hello\0".


Why is dtostrf() not working for this one value? I'm building a weather station using an ESP32 and BME280. I'm feeding the data via MQTT and Python into a database that is then used to make a nice dashboard for the data.

The MQTT message needs to be a char, and the sensor readings are floats, so I'm using dtostrf() to convert them. This works fine for the temperature and pressure readings, but for some reason not for the humidity reading.

I declare my variables:

float temp;
float hum;
float pres;

char mqttTemp[6];
char mqttHum[6];
char mqttPres[5];

Then I get my readings:

temp = mySensor.readTempC();
Serial.print("Temp: ");
Serial.print(temp);
hum = mySensor.readFloatHumidity();
Serial.print("Hum: ");
Serial.print(hum);
pres = mySensor.readFloatPressure();
Serial.print("Pres: ");
Serial.print(pres);

This returns:

Temp: 25.57 Hum: 40.15 Pres: 97684.39

Then I run the results through the function:

dtostrf(temp,4,2,mqttTemp);
dtostrf(hum,4,2,mqttHum);
dtostrf(pres,5,0,mqttPres);

Then I output these to Serial:

Serial.print("Temperature: ");
Serial.print(mqttTemp);
Serial.print("Humidity: ");
Serial.print(mqttHum);
Serial.print("Pressure: ");
Serial.print(mqttPres);

Which gives me:

Temperature: 25.57
------------------------------
Humidity:
------------------------------
Pressure: 97684

There is also no message sent via MQTT for humidity, but it works perfectly for the other two readings. What gives?

What is happening is that the variables you declared for mqttTemp etc are stored in memory something like this

variable   memory address
mqttPres @ 1000-1004 (5 bytes)
mqttHum  @ 1005-1010 (6 bytes)
mqttTemp @ 1011-1015 (6 bytes)

For a start, you only have enough room (with the mandatory NUL byte string terminator) for 4, 5 and 5 characters

When you convert pressure, the NUL byte is being placed as the first byte in mqttHum, therefore, when printing mqttHum you get an empty string output (since the first byte is NUL)

To really see what's happening, here's some code that illustrates the issue

char mqttTemp[6] = "TTTTT";
char mqttHum[6] = "HHHHH";
char mqttPres[5] = "PPPP";
void setup() {
  float temp = 25.57;
  float hum = 40.15;
  float pres = 97684.39;

  Serial.begin(74880);
  // put your setup code here, to run once:
  delay(100);
  Serial.println("before");
  printThem();
  dtostrf(temp, 4, 2, mqttTemp);
  Serial.println("converted temp");
  printThem();
  dtostrf(hum, 4, 2, mqttHum);
  Serial.println("converted hum");
  printThem();
  dtostrf(pres, 5, 0, mqttPres);
  Serial.println("converted press");
  printThem();
}
void printThem()
{
  Serial.print("mqttPres ");
  Serial.print((unsigned long) &mqttPres, DEC);
  Serial.print(": ");
  for (int i = 0; i < 5; i++) {
    Serial.print((int) mqttPres[i], DEC);
    Serial.print(' ');
  }
  Serial.println();

  Serial.print("mqttHum  ");
  Serial.print((unsigned long) &mqttHum, DEC);
  Serial.print(": ");
  for (int i = 0; i < 6; i++) {
    Serial.print((int) mqttHum[i], DEC);
    Serial.print(' ');
  }
  Serial.println();

  Serial.print("mqttTemp ");
  Serial.print((unsigned long) &mqttTemp, DEC);
  Serial.print(": ");
  for (int i = 0; i < 6; i++) {
    Serial.print((int) mqttTemp[i], DEC);
    Serial.print(' ');
  }
  Serial.println();
}

void loop() {
  delay(50);
  // put your main code here, to run repeatedly:

}

The above outputs the following:

before
mqttPres 1073644748: 80 80 80 80 0
mqttHum  1073644753: 72 72 72 72 72 0
mqttTemp 1073644759: 84 84 84 84 84 0
converted temp
mqttPres 1073644748: 80 80 80 80 0
mqttHum  1073644753: 72 72 72 72 72 0
mqttTemp 1073644759: 50 53 46 53 55 0
converted hum
mqttPres 1073644748: 80 80 80 80 0
mqttHum  1073644753: 52 48 46 49 53 0
mqttTemp 1073644759: 50 53 46 53 55 0
converted press
mqttPres 1073644748: 57 55 54 56 52
mqttHum  1073644753: 0 48 46 49 53 0
                     ^ ======== note the leading 0
mqttTemp 1073644759: 50 53 46 53 55 0

The simplest fix, of course, is to declare your variables with the correct size

char mqttTemp[7]; // because -10.00 takes 6 characters + 1 for NULL
char mqttHum[7];  // because 100.00 takes 6 characters + 1 for NULL
char mqttPres[6]; // because 97684 takes 5 characters + 1 for NULL - if pressure can reach 100000 then use 7 here as well

and then use dtostrf correctly, i.e. the second argument is the total width, including . and a possible -

dtostrf(temp,6,2,mqttTemp);
dtostrf(hum,6,2,mqttHum);
dtostrf(pres,5,0,mqttPres);


I am not able to use ESP8266 12E with Arduino I am doing my engineering degree. I want to make a project connecting multiple ESP8266 with a router and control multiple relay boards. I am unable to use ESP8266 12E with Arduino. I used this connection shown in the link below, but it didn't work. So please help me with the solution. I also referred to all possible posts, but it didn't help. Please help me as soon as possible.

Connection:

post: How to connect ESP8266 12e directly to Arduino Uno (without shields)

I agree with Paul, you shouldn't use the Arduino, you can get break out boards at £1 for 10, but that's not what your problem is...

You are using a couple of resistors to do the level shifting taking the 5V to 3.3V.  This is a bad plan, you need a proper bidirectional level shifter, particularly at higher baud rates, i.e. above 1000.

You are supplying the top VCC rail with both 3V from the batteries and 3.3V from the Arduino, not the best plan IMO.

You are not supplying the Arduino with any power, I guess this is a drawing error but just in case it isn't I though I best mention it.

You have no level shifting on the Arduino's Rx line.  Its not technically needed, but you might require it particularly when the batteries are going flat.

You are using batteries and that's not a great plan.

Have you configured the ESPs using the AT command set, since you won't program them.

Just for the record the ESP has more memory it has a faster processor (80MHz) and you can still use the Arduino IDE.  You should be able to pick up boards to mount the ESPs so you can use them more easily for less that the price of the level shifters, but its your call.


Serial.Write(buf,Len) how to read Serial sended array of byte hello i'm trying to send array of byte with Serial.Write(buf,Len) but don't know hot to read this code with receiver.

SENDER code:

byte buf[4]={1,2,3,4};
void setup(){
Serial.begin(250000);
}

void loop(){
Serial.write(buf,4);
}

RECEIVER code (WRONG)

byte buf[4];

void setup() {
  Serial.begin(250000); // how suggest

}

void loop() {
  int i = 0;

  if (Serial.available()) {
    Serial.readBytes(buf,4);
    Serial.print(buf[0]);
    Serial.print(buf[1]);
    Serial.print(buf[2]);
    Serial.print(buf[3]);
  }
}

How to receive this ??

You have two issues:

Firstly the transmitter is set to 250000 baud (a non-standard rate) while the receiver is set to 9600 baud. Both need to be set to the same rate.

Secondly the transmitter is constantly sending data and the receiver is constantly reading it, there is no way to ensure the two are synchronized. So your receive buffer could well end up being the end of one set of data and then the start of the next e.g. 3,4,1,2. If all you are sending is the same loop over and over this doesn't matter but for real world data it's an issue. If you have a value which you know will never be in your data (e.g. 0 or 0xff) then you can use that as a start of data marker, if not then things get a little more tricky.


What's the best way to operate a remote control circuit board? What would be the best way of using an Arduino to operate the pictured remote control circuit board? My initial instinct would be to leave the batteries in the remote and use a separate transistor for each of the five switches, connecting wires (solder or electrical tape) to the two sides of each button and the base to an Arduino output pin. I'm certainly not an expert, so I wanted to confirm whether (a) that would work and (b) if there's a much better way. The control is normally powered by two AAA batteries.

Edit: There's also a small capacitor on the underside of the circuit board, if that changes anything.

Thanks in advance for your help
Note: I've tried to simply record and emit the IR signals from the remote using my Arduino, but have thus far been unsuccessful, so want another way of using the Arduino to control my fan: Unable to control fan with IR circuit despite capturing and reproducing the IR transmissions

All the right sides of the buttons are connected to the negative of the battery (that is ground). So you connect the remotes GND to the Arduinos GND.
Next solder five wires to the left side of the buttons. You can do this by scraping away a bit of the green solder mask that's on top of the trace going to that button pad. Or find out which pin on the IC goes to the button, and solder a wire to that leg.
I wouldn't mess with the black stuff (graphite?) on top of button pad. That way you can always return the remote to it's original function.
Then connect those wires to the Collectors of NPN transistors. The Emitters all connect to GND. The Bases (via a resistor) to the Arduino pins.
Alternatively, you can connect them directly to the Arduino pins. But you'd have to be careful to never set the pin to HIGH, as the remote won't like 5V on it's input pins while it is itself running on only 3V. You "press" the button by setting the pin to OUTPUT. After a "press" you set it back to input.
To prevent accidentally supplying 5V to the button pin, you can also use diodes (instead of transistors described above). Put the diode between the Arduino pin, and the button wire, pointing towards the Arduino. That way current can only go towards the Arduino. Then you can safely use digitalWrite.


Applying 5v to analogWrite Pin I am controlling a motor with an Arduino Nano, that motor is controlled by Cytron MD-10c motor controller.

i want to wire a momentary switch in parallel with the analog output PIN from the Arduino and PWM input on the MD-10c, the switch will connect the 5v output from Arduino to the PWN input on the MD-10c. Basically an override to go full power.

Is there any risk of damage with this sort of wiring with the switch?

Yes, depending on the current that will flow.

If your PWM output pin is connected to 5V without a current limiting resistor, nothing will happen during the HIGH phases of the PWM, but you will short the input pin during the LOW phases.

According to the manual of your motor controller, you should be able to use a current limiting resistor to prevent this.
Since the ATMega328P on your Arduino Nano can sink a maximum of 40 mA, that resistor should be at least 125 Ohms. A resistor larger than 1 kOhm should work fine.

The other option would be installing a diode between your Arduino Nano and the motor controller.
This does not require the use of a current limiting resistor.
The motor controller would still work, since the minimal voltage for the pin state to be detected as HIGH is 3V (1), much lower than the ~4.3V you're left with after a diode.


Can I make delayMicroseconds more accurate? I'm trying to bit bang DMX data and that requires 4us pulses. Not having much luck with the results I'm checking to see how good the Arduino is at delaying... Seems to be pretty terrible at it.

Here's a quick little test I did:

unsigned long ptime;

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

void loop() {
  ptime = micros();
  delayMicroseconds(4);
  Serial.println(micros() - ptime);

  delay(1000); //just to keep the serial monitor from going nuts
}

And the results:

  8 4 8 4 4 4 4 4 8 8 8 8 4 8 8 4 4 8 4 4 4 8 8 8 4 8 4

I was kinda shocked at just how bad it's accuracy is. It's double the time I wanted to delay, but it's not even consistent to where I could just divide by 2!

Is there anything I can do to get correct, consistent results?

As explained in the previous answers, your actual problem is not the
accuracy of delayMicroseconds(), but rather the resolution of
micros().

However, to answer your actual question, there is a more accurate
alternative to delayMicroseconds(): the function _delay_us() from
the AVR-libc is cycle-accurate and, for example

_delay_us(1.125);

does exactly what it says. The main caveat is that the argument has to
be a compile-time constant. You have to #include <util/delay.h> in
order to have access to this function.

Note also that you have to block the interrupts if you want any kind of
accurate delay.

Edit: As an example, if I were to generate a 4 µs pulse on PD2
(pin 19 on the Mega), I would proceed as follows. First, notice that the
following code

noInterrupts();
PORTD |= _BV(PD2);   // PD2 HIGH
PORTD &= ~_BV(PD2);  // PD2 LOW
interrupts();

makes a 0.125 µs long pulse (2 CPU cycles), because that's the
time it takes to execute the instruction that sets the port LOW. Then,
just add the missing time in a delay:

noInterrupts();
PORTD |= _BV(PD2);   // PD2 HIGH
_delay_us(3.875);
PORTD &= ~_BV(PD2);  // PD2 LOW
interrupts();

and you have a cycle-accurate pulse width. It is worth noting that this
cannot be achieved with digitalWrite(), as a call to this function
takes about 5 µs.


using enums in functions Given the following enums

enum RelayState { RELAY_OFF = HIGH, RELAY_ON = LOW };
enum class CrossingZoneState: uint8_t {
    CROSSINGZONE_CLEAR = 0, // no train in crossing area, also initialized state
    CROSSINGZONE_OCCUPIED = 1, // train detected by the entry sensor
    CROSSINGZONE_EXITING = 2  // train detected by the exit sensor, when sensor clears, state= Clear
};

Where RELAY_OFF = HIGH, HIGH is #define HIGH 0x1 which I assume is a C++/Arduino constant? because I didn't define it. And RELAY_ON = LOW, LOW is 0x0

in the following function I get the error that follows.

CrossingZoneState CheckEntrySensor(uint8_t esp) {
    //esp, short for entry sensor pin
    if (digitalRead(esp) == HIGH)
    {
        state = CrossingZoneState::CROSSINGZONE_CLEAR;
        return state;
    }
    else if (digitalRead(esp) == LOW)
    {
        state = CrossingZoneState::CROSSINGZONE_OCCUPIED;
        return state;
    }
    // if the digital read errs, return the current state so it re-runs
    return state;
};

boolean throwRelayAndCheckStatus(uint8_t relayNumber, RelayState relayState)    {

    int testInt = 0;
    if (relayState == RelayState::RELAY_OFF)
    {
        testInt = 1;
    }
    digitalWrite(relayNumber, relayState);
    if (digitalRead(relayNumber) == testInt) {
        return true;
    };
    return false;
};

I tried having RelayState be an enum class as well but was getting similar type errors. Here is the error from VS2015 with the code shown above.

  Compiling debug version of 'ModelRRXingStateMachine' for 'Arduino/Genuino Uno'
  ModelRRXingStateMachine.ino:11:55: error: 'RelayState' has not been declared
  :boolean throwRelayAndCheckStatus(uint8_t relayNumber, RelayState relayState)
  ModelRRXingStateMachine.ino:2:1: error: 'CrossingZoneState' does not name a type
  :CrossingZoneState CheckEntrySensor(byte esp)
  Error compiling project sources

I'm not a professional programmer and am new to C++, usually writing in C# or VB.Net so I'm not sure what the compiler is looking for here, both enums are declared and one is declared with a type. Also, the VS code editor is showing no errors, the errors shown above show up in the error window when I try to build.

The solution was to move the enum declarations to a header file, due to the fact this was a VM add-in issue which will be resolved once they've implemented arduino version 1.6.8.

Adding this code to a header file and removing it from the main file resolved the issues and the code builds and runs.

// ModelRRCrossing.h

#ifndef _MODELRRCROSSING_h
#define _MODELRRCROSSING_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
#else
    #include "WProgram.h"
#endif
#pragma once
// Arduino Digital I/O pin numbers for MEGA
//note: digital pins 30-45
//MEGA is a MUST for this project
enum {
    Relay1 = 30, Relay2 = 31, Relay3 = 32, Relay4 = 33, Relay5 = 34, Relay6 = 35,
    Relay7 = 36, Relay8 = 37, Relay9 = 38, Relay10 = 39, Relay11 = 40,
    Relay12 = 41, Relay13 = 42, Relay14 = 43, Relay15 = 44, Relay16 = 45
};

enum RelayState { RELAY_OFF = HIGH, RELAY_ON = LOW };
enum class CrossingZoneState : uint8_t {
    CROSSINGZONE_CLEAR = 0, // no train in crossing area, also initialized state
    CROSSINGZONE_OCCUPIED = 1, // train detected by the entry sensor
    CROSSINGZONE_EXITING = 2  // train detected by the exit sensor, when sensor clears, state= Clear
};

#endif


Avrdude Verification Error while flashing Arduino Mega code I'm working with an Arduino Mega 2560 and am getting the following error at compile time:

  avrdude: verification error, first mismatch in byte 0x0000 0x14! =
  0x25 avrdude: verification error; content mismatch

I've already changed the COM port and also restarted an IDE.

I have made Jot's comment into an answer in the hope that it helps someone.

First mismatch in byte 0x0000. [This is] the first byte that goes wrong. That means that not even a single byte passes the verification.

Perhaps the cause is one of these:

A cheap clone with a bad bootloader.
An old bootloader.
A bug, perhaps a bug with the size of the code or ram, for example the code at the border of 32k or 64k.
Maybe the voltage of the Arduino board is too low. Measure it. It must be above 4.5V.
Maybe a bad USB cable.
Wrong USB driver.
Board is too cheap and is missing decoupling capacitors.


Arduino original motor shield can not supply enough torque to the motor? I am using original Arduino motor shield L298P with Arduino uno.

I disassembled an electric screw driver which came out with a 4.8 v battery pack and a 4.8v specified DC motor.

I connected battery pack to the Vin and Ground pins of the motor shield, and connected the DC motor to A channel of the shield.

The thing is when I run a test code with PWM 255, the torque of the motor is way too low compared to connecting the motor directly to the battery pack. I also changed the batteries to a common 1.2v rechargeable 4 batteries connected in parallel. The result is the same.

What might be going wrong?

I also paste the code I am using below. Thanks in advance.

const int motorPin = 3;
int Speed;
int flag;
void setup()
{
pinMode(motorPin, OUTPUT); //Set pin 3 as an OUTPUT
Serial.begin(9600); //Init serial communication
//Print a message:
Serial.println("Give a number from 50 to 255."); //Why minimun value 50?     Because with values below 50 the motor doesn't spin ;)
Serial.println(""); //Blank line
}

void loop()
{
//Check if incoming data is available:
if (Serial.available() > 0)
{
  // If it is, we'll use parseInt() to pull out only numbers:
  Speed = Serial.parseInt();
  flag=0;
}

//Valid range is from 50 to 255
if (Speed>=50 && Speed<=255){
    //Send PWM value with analogWrite to Arduino pin 3 and print a message to serial monitor
    analogWrite(motorPin, Speed);
    //Print message only once
    if (flag==0){
        //Print PWM value
        Serial.print("Motor spinning with ");
        Serial.print(Speed);
        Serial.println(" PWM");
        flag=1;
    }
}

delay(1000);
}

According to the motor shield page:

  To avoid possible damage to the Arduino board on which the shield is mounted, we reccomend using an external power supply that provides a voltage between 7 and 12V. If your motor require more than 9V we recommend that you separate the power lines of the shield and the Arduino board on which the shield is mounted. This is possible by cutting the "Vin Connect" jumper placed on the back side of the shield. The absolute limit for the Vin at the screw terminals is 18V.

According to you:

  I disassembled an electric screw driver which came out with a 4.8 v battery pack and a 4.8v specified DC motor.

  I connected battery pack to the Vin and Ground pins of the motor shield, and connected the DC motor to A channel of the shield.

That's a lot less than 7V.

Also, from the motor shield page:

  Max current   2A per channel or 4A max (with external power supply)

How much current does your screwdriver use?


Arduino analog input to iphone notification I need some help :)

Is it even doable?
Is there anyone who wants to help me program it?

My wish:
I want to receive a iphone notification when 1 arduino analog input drop from 5 to 0 volt.
Then (later) when the voltage goes back to 5V i want another message.
It needs to be over Wifi (not BT).
Is there anyone that can help me with this?
Thanks in advance

It is totally doable, but we cannot give detailed tutorials here, since this is a simple Q&A site. So I will point you to a direction, that can lead you to the solution.
When building IOT devices with Arduino (and thats exactly, what you are doing) there are 2 internet services, that are commonly used for getting information from the device to other devices (like your phone):

Blynk
IFTTT (means If This Then That)

Both have apps and can be used to push notifications, when your IOT device does a webrequest to the service. There are also libraries for Arduino available (at least for Blynk). There are many tutorials out there, so I suggest, that you search for yourself and try some of them.
For the hardware of your IOT device, I would suggest an ESP board, because they already have Wifi build in, for example the ESP32 gives you great IO capabilities.


Laser emitter + receiver for Arduino (Arduino to Arduino communication) I'm working on a project using 2 Arduinos connected to 2 computers to demo Serial to Serial communication.

We're using Arduino Uno connected to the computer via Serial and software serial for inter-Arduino communication. We used wires to connect software serial RX & TX lines, but we'd like to connect these pins to a laser transmitter and receiver.

We're trying to show wireless communication using an optical medium, which is why we wanted to use a Laser transmitter and receiver.

We're trying something like the setup in this YouTube video $3 laser transmits audio over 100m (Arduino)

Any idea how high a baud rate we will be able to achieve using the transmitter and receiver?

Receiver: Laser Sensor Module non-modulator Tube Laser Receiver

Transmitter: 5V ... Board For Arduino AVR ... KY-008 Laser Transmitter

Any idea how high a baud rate we will be able to achieve using the transmitter and receiver?

Looks like the receiver module has a low-pass filter. That could reduce the baud-rate depending on the RC-factor (10 Kohm * 10 nF gives a cut-off frequency of 1.6 kHz). I would recommend checking the actual components. The above is a guesstimate.

Cheers!


How Should I Send Data to My Laptop from Multiple Arduinos? I'm working a project which involves reading multiple RFID tags, from multiple directions, at the same time. Because of the multiple directions, I need to use multiple antennae. Because of the multiple tags, I need to use a simultaneous RFID reader.

Unfortunately, the wiring of the simultaneous RFID reader doesn't support multiple antennae, so each antenna will need its own simultaneous RFID reader. It seems likely - although I'm waiting for confirmation on this - that each RFID reader will have to have its own Arduino as well. What's the least horrible way of sending the data those antenna-reader-Arduino combinations are gathering to a laptop?

If this makes a difference, the laptop I'm going to be sending the data to will be running Ubuntu, and I'd like to collect the data using Python's pyserial package. Once I've got the data in a Python program, we're home and dry.

There are multiple solutions but the simplest one is probably to use Software serial, I2C, or SPI. The idea is basically the same for any of the protocols. You select one Arduino which is gonna be the master and be connected to the laptop. Than using any of those interfaces you connect the Arduino boards in to a chain. Than you can ask the slave Arduino boards if they have new data one by one. If they do they send it and the master forwards it to the laptop. In this way all the slave boards will wait until they are asked for data and thus avoid collisions of data streams.


Record Ping time using ultrasonic sensors and calculate speed I'm trying to find the speed of remote control toy car passing by two ultrasonic sensors. I need help on my code and suggestion on max speed car should go to record time. Opposite direction not accounted for and ideally the car would pass by both sensors without stopping. I know laser reading is better for this simulation but I need it for a presentation in two weeks.

Here are the steps I was recommended to use:

Get the duration of pulse for sensor 1 and convert to distance
if the distance the object is within the desired threshold (you detected something)
2a. record the system time at which object was detected
2b. start a loop to for sensor 2
Within the sensor 2 loop keep getting the duration/distance until an object is detected or too much time has passed
If an object is detected record the system time
Subtract the two system times (from sensor 1 and 2) and use that to determine object speed

#define sensor_distance .111 //distance between two sensors in meters
const int trigPin1 = 3;
const int echoPin1 = 4;
const int trigPin2 = 5;
const int echoPin2 = 6;

double first_time = 0;
double second_time = 0;
double final_time = 0;

double vehicle_speed = 0;

void setup() {

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  Serial.begin(9600);
}

void loop() {

double ping_time(int trig1, int echo1, double first_time);
double ping_time(int trig2, int echo2, double second_time);

final_time = second_time - first_time;
vehicle_speed = sensor_distance/final_time;
}

double ping_time(int trig, int echo, double record_time) //function used to record time.
{
  long duration, distance;

   digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);

  duration = pulseIn(echo, HIGH);
  distance = duration * 0.034 / 2;

  if (distance < 35) {
    Serial.print(distance);
    Serial.println("  cm");
    record_time = millis();
    record_time = record_time/100; //Divided by 100 to get time in seconds

    return record_time;

  }
  if (distance > 35) {
    Serial.println("OUT OF RANGE");
  }
  delay(20);
}

You can try this, but I don't know if this gonna works or not since it is "imaginary-based"

const int trigPin1 = 3;
const int echoPin1 = 4;
const int trigPin2 = 5;
const int echoPin2 = 6;

void setup() {

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  Serial.begin(9600);
}

void loop()
{
    if (ultraSonicdetect())
    {
        while (ultraSonicdetect(trigPin1,echoPin1)); // wait the car pass ultrasonic 1
        first_time = millis();
        while (!ultraSonicdetect(trigPin2,echoPin2)); //wait the car approach ultrasonic 2
        second_time = millis();

        //here you can calculate the speed, time needed to travel from ultrasonic 1 to ultrasonic 2
        //can be calculated from
        //(speed = second_time - first_time) / sensor range
    }
}

bool ultraSonicdetect(int trig, int echo) {
   long duration;
   float distance;
   digitalWrite(trigPin, LOW);
   delayMicroseconds(60);
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(60);
   digitalWrite(trigPin, LOW);
   duration = pulseIn(echoPin, HIGH);
   distance = (duration * 0.034) / 2;
   if (distance<35) return true; else return false;
}


Easy way to upload sketches using MIDI (without RX pin removed) I noticed when I use sketches with MIDI (using RX/TX), before uploading I have to remove every time the RX wire ... is there an easy way to prevent this?

(I'm thinking about making a push button/toogle for this to prevent it, but maybe there is an easier way).

Update: I use an Arduino Uno

To allow the bootloader on the Arduino MCU to communicate with the USB chip, the TXD/RXD pins are connected:

These connections have 1 kΩ resistors so that the signals of the USB chip do not interfere with your own hardware too much. However, this means that your own hardware can easily override those signals.

In this case, your MIDI hardware actively drives the RXD line to a high level.

You is no way to work around this in software.
You could try to replace the optocoupler's pull-up resistor (270 Ω) with a 10 kΩ resistor, which would make the USB controller's signals ten times stronger than the MIDI ones, but this might make the signal edges too slow.
To reliably prevent conflicts, you have to add a disable function to the MIDI receiver, or power it down, or disconnect it.


Atmega328P-PU: Programmer is not responding Few days ago, I built my own custom Arduino on the breadboard. It is built according to tutorial on http://www.crash-bang.com/resource/breadboard-arduino/. The Atmega328P-PU is already burned with the Arduino bootloader with simple blink sketch.

For the programmer, I decided to use the Arduino USB2Serial. Again, it is connected as shown on crash-bang site. Problem is I get this error when uploading a different sketch:

avrdude -Cavrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:build244630154737317489.tmp/sketch_may23a.cpp.hex:i

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 "avrdude.conf"

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

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

     Programmer Type : Arduino
     Description     : Arduino
     Hardware Version: 3
     Firmware Version: 4.4
     Vtarget         : 0.3 V
     Varef           : 0.3 V
     Oscillator      : 28.800 kHz
     SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: reading input file "build244630154737317489.tmp/sketch_may23a.cpp.hex"
avrdude: writing flash (450 bytes):

Writing | avrdude: stk500_recv(): programmer is not responding

Most of the time I do not even get to this point and just end up with something like:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xf5

What I have done so far:

I already tried to reset Arduino just before uploading the sketch.
According to the avrdude, bootloader is fine.
Reinstalled drivers, Arduino IDE
Changed the USB cable and connected it to another USB slot
Burned new bootloader using ArduinoISP

Thank you for help.

I've read the tutorial at the crash-bang website and found two issues with it. The first issue is minor and probably won't fix your upload issue.

Step 3 says to connect +ve rail –> AVCC (pin 20) and +ve rail –> AREF (pin 21). You can leave those pins not connected. A really awesome guy named Julian ILETT has a video on youtube showing a homemade Arduino using the bare minimum connections needed. https://www.youtube.com/watch?v=sNIMCdVOHOM.

The second issue with the tutorial is in Step 5, "Connect the DTR pin of the FTDI, via a 0.1uF capacitor to pin1 on the ATmega.". A lot of people claim this works, but it doesn't work for everyone. It doesn't work for me and I have 2 of the identical FTDI programmers used in the tutorial. If you watch Julian's video starting at 12:48, you will see that he had trouble uploading a sketch using the DTR / 0.1uf capacitor method. He is using a different USB to TTL device but I have one of the identical devices he was using and the 0.1uf cap method doesn't work for me.

The solution to the upload issue is to use a switch to reset the Atmega328P-PU. Like the tutorial says, use a 10k ohm resistor connected to +5V and pin 1 of the Atmega328P. Now connect a one terminal of a N.O. momentary switch to ground and the other to pin 1 of the Atmega328P. To upload your sketch, click the upload button on the Arduino IDE window. As soon as the Debug window says "Binary Sketch Size…", press the reset button and hold it down for 1/2 a second then release.

I've just joined arduino.stackexchange.com a week ago so my answer may be a bit late. Hopefully this helps people in the future.


How do I scroll through the LCD vertically with joystick? I have a device I'm working on and the only issue I'm running into is I can't manage to figure out how to get my LCD display to move around vertically with the joystick I have attached to it. I have a feeling with a tip this could be a very simple fix, but I'm just stuck. So the brief of this is that I need someone to fill in the ???'s for me provided in my example code.

//Include the LCD Library.
#include <LiquidCrystal.h>
#include <Wire.h>
//Declare the LCD object and define pins.
#include <MFRC522.h>
#include <SPI.h>

#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

#define SAD 10
#define RST 5

//Ignore The below line it is for the master code
#define I2C_ADDR    0x27 // <<----- Add your address here.  Find it from I2C Scanner
#define BACKLIGHT_PIN     3
#define En_pin  2
#define Rw_pin  1
#define Rs_pin  0
#define D4_pin  4
#define D5_pin  5
#define D6_pin  6
#define D7_pin  7

int n = 1;

LiquidCrystal_I2C  lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

void setup() {

//Booting the LCD
  lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
  lcd.setBacklight(HIGH);
  lcd.home (); // go home
  lcd.cursor();

//Starting settings
  lcd.begin(1,0);
  lcd.clear();

}

//Sometimes you have to hit reset on the device

//Joystick Defaults X=484 Y=513

void loop() {
  lcd.setCursor(0,0);
  lcd.print("Example");
  delay(100);

for (int positionCounter = 0; positionCounter = 1; positionCounter++) {
if(analogRead(1) > 584) {
  lcd.scrollDisplayLeft();
  delay(30);
  } else if(analogRead(1) < 384) {
    lcd.scrollDisplayRight();
    delay(30);
  } else if(analogRead(0) < 413) {
     lcd.???????????????????();
     delay(30);
  } else if(analogRead(0) > 613) {
     lcd.??????????????????();
     delay(30);
    }
  }
}

The LCD library provides easy functions that activate commands in the LCD itself.  The LCD doesn't have functions that do what you want, so there is no simple vertical scrolling like you're suggesting.

If you need to have it, you'll need to re-write the screen with the content you want to display when the user scrolls around. I can't make any specific suggestions as I don't know the reason you need to scroll around the display this way, but one comprehensive method would be to create a buffer of data the LCD should be displaying, then scroll it using software (move the bytes around the way you want) and then send that buffer to the LCD when it changes.

There may be other more applicable or easier tricks, but that would largely depend on your specific use case and user interface design.


Arduino HTTP Request Fails Slow Cellular Connection Setup:

Arduino Mega 2560 w/ Wiznet W5500 Ethernet Sheild
Using TP-Link TL-MR6400 LTE router to connect to internet over cellular connection in Uganda.

Using an HTTP Post with the following,

client.println("POST /hook HTTP/1.1");
client.print("Host: "); client.println(server);
client.println("Accept: */*");
client.print("Content-Type: text/html;");
client.println("User-Agent: Arduino/1.0");
client.println("Connection: close");
client.print("Content-Length: ");
client.println(PostData.length());
client.println();
client.println(PostData);

where PostData is a String and Ethernet2 is the library used.

This works just fine from the US to the same AWS server, or a https://requestbin.com/ instance.

When testing from Uganda using a Raspberry Pi and curl it works fine.

$ curl -vs -d 'ABCDEFG' -H "User-Agent: Arduino/1.0"  -H "Content-Type: text/html" -H "Connection: close"   http://<server here>/hook
*   Trying <ip here>...
* TCP_NODELAY set
* Connected to <server here> (<ip here>) port 80 (#0)
> POST /tg HTTP/1.1
> Host: <server here>
> Accept: */*
> User-Agent: Arduino/1.0
> Content-Type: text/html
> Connection: close
> Content-Length: 7
>
* upload completely sent off: 7 out of 7 bytes
< HTTP/1.1 200 OK
< Access-Control-Allow-Origin: *
< Content-Type: application/json; charset=utf-8
< Date: Tue, 06 Aug 2019 21:06:49 GMT
< x-pd-status: sent to primary
< X-Powered-By: Express
< Content-Length: 16
< Connection: Close
<
* Curl_http_done: called premature == 0
* Closing connection 0
{"success":true}

I even tried an HTTP GET example from the Ethernet2 library,

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

It worked just fine in the US but in Uganda I get,

My IP address: 192.168.1.177

connecting...

connecting...

connecting...

I increased the time between requests here to 100 seconds where it is listening for the whole time inbetween.

It seems that client.connect(server, 80) is successful and the client.print messages go through but the message never reaches the server so there is no response. My AWS server does not recieve the request and this is the same for the requestbin instance. This behavior is mirrored in all my Arduino tests.

I thought the ISP might be blocking but the RPi can send nearly the same message. I thought maybe a timeout somewhere but I can not find where with my tests. I thought my message was too long but I reduced the size to only 10 characters with the same results.

Trying to figure out why the Arduino HTTP request cannot reach any webhooks from Uganda and how to fix it if possible. Different ISP, slower connection, cellular connection?

Any help would be appreciated.

Buffering and flush()

Many arduino libraries suffer of slow communication because the authors didn't use buffering. To not to send every small piece of data over a connection with overhead of protocol bytes use buffering. Data are collected until the buffer is full and then the collected data are send and the buffer is ready for next bytes. The flush() functions sends the buffer even if it is not full, but you do not have more data. (The flush() 'dilemma' was resolved and in Arduino core classes the flush() method is declared in Print class which is the Arduino standard interface for output streams.)

My StreamLib library offers a BufferedPrint class which wraps the target stream and buffers the data to be send over the target stream. Of course, do not forget to use flush() after last data printed.

HTTP data length

It is common practice in Arduino sketches to not to send the Content-length header with POST requests. In most cases it is because when the HTTP headers are send, the size of data is not known. The WebServer then doesn't know if it received all the data and waits until the connection is closed or timeout is reached. It leads to long time until a Web Server sends the response to requesting Arduino sketch.

If the data can be prepared to a string in memory, fill the Content-length HTTP header.

If the data to be send as response or in POST request wouldn't fit into available memory, ChunkedPrint from my StreamLib can be used with HTTP chunked Transfer-Encoding. And ChunkedPrint is an extension of BufferedPrint so the Web Server handles your request without hesitating.