texts: Reading Serial Data Using readBytes() and Use of Serial.read()

texts:
I'm trying to mix Serial.read() and Serial.readBytes() when reading over one of the Serial ports on my Arduino Due.
I thought that using Serial.read() would clear what is on the serial, and then subsequent reads by readBytes() would not pick up what has already been read by the Serial.

The main reason I'm trying this approach is because large Serial reads can be unstable using the Arduino supplied Serial.read() - I've checked the Serial buffer with a logic analyzer, so I know that the data is on the Serial line, but Serial.read() drops some bytes.

Hence why I want to use Serial.readBytes().

Here's what I'm doing:

#define FIXED_LENGTH 10
char * buffer, * bp;
int index, i, bufSize;
while(1)
  {
  if(Serial3.available())
  {
    data = Serial3.read();
    Serial.print(data,HEX); //Check the data received
    buffer[index]=data;
    index++;

    if(index == FIXED_LENGTH){
       //...code to calculate bufSize from buffer...//
       bp = (char*)calloc(1,bufSize); //calloc bp size
       Serial3.readBytes(bp,bufSize); //read the rest of what's on the serial
       break;
    }
  }
  }

I get the correct output from the first part of the code - that is, it correctly calculates bufSize from buffer. But when I try to store the following length into bp, it gives me more or less the first output that I have already read on the first few passes!

Example:

Data coming in over Serial3.read() [10]: 0123456789

The next characters in Serial3 are [6]: ABCDEF

Stored into bp using Serial3.readBytes() [6]: 000045

Do I need to flush Serial3 before attempting to read the next set of bytes off of it? Do I need to wait/set a timeout before advancing to the next operation?


texts: reversing DC motor rotation using TWO limit Switches Problem !! need help

texts:
I'd like to write a code for reversing DC motor rotation direction as follows:

Start the motor rotation clockwise (CW).
When reach Limit Switch (CW) → motor will stop for 5 sec.
after 5 sec. of stopping → the motor will rotate in counter clockwise direction(CCW).
When reach Limit Switch (CCW) → motor will stop for 5 sec.

and repeat point 1, 2, 3 and 4...

Actually I wrote a code for reversing the motor direction using two limit switches and it is working good. But when I added delay the motor did not stop using the limit Switches and continue to rotate...
If any one can help...
Here is my code for reversing the direction with out delay 5 sec. My limit SWs are connected on Normal Open.

int sw1, sw2, sw3;
const int LM1 = 0;
const int LM2 = 1;
const int LM3 = 6;
const int CW = 10;
const int CCW = 9;
const int Buzzer = 7;

void setup() {
  pinMode(LM1, INPUT);
  pinMode(LM2, INPUT);
  pinMode(LM3, INPUT);
  pinMode(CW, OUTPUT);
  pinMode(CCW, OUTPUT);
}

void loop(){
  sw3 = digitalRead(LM3);
  sw1 = digitalRead(LM1);
  sw2 = digitalRead(LM2);

  if (sw1 == LOW && sw2 == HIGH) {
    do {
      digitalWrite(Buzzer, HIGH);
      digitalWrite(CW, HIGH);// change the direction of rotation (DOWN Movement)
      digitalWrite(CCW, LOW);

      sw2 = digitalRead(LM2);
    } while (sw2 == HIGH);
  }
  else if (sw1 == HIGH && sw2 == LOW) {
    do {
      digitalWrite(Buzzer, HIGH);
      digitalWrite(CW, LOW);// change the direction of rotation (UP Movement)
      digitalWrite(CCW, HIGH);

      sw1= digitalRead(LM1);
    } while (sw1 == HIGH);
  }
}


texts:
I am tring to use ShorTie8's new arduino ARM installer on my RPI B+ by copying this into my terminal:

  cd

  sudo apt-get update -y && sudo apt-get dist-upgrade -y

  wget https://raw.githubusercontent.com/ShorTie8/Arduino_IDE/master/Arduino_IDE_builder.bash

  chmod +x Arduino_IDE_builder.bash

  sudo ./Arduino_IDE_builder.bash

  sudo Arduino/build/linux/work/./arduino

  sudo Arduino/build/linux/work/./install.sh

  sudo apt-get install -y mercurial subversion build-essential gperf bison ant texinfo zip automake flex libusb-dev libusb-1.0-0-dev libtinfo-dev pkg-config libwxbase3.0-dev libtools

But Getting The following Error at sudo ./Arduino_IDE_builder.bash

  echo -e '\n\nConfiguration values\n\n'

  Configuration values

  Stable=1.6.7
  Update_me=yes
  Silence_is_Golden=yes
  echo -e '\n\nSystem check\n\n'

  System check

  ++ date
  + start_time='Sat 13 Feb 11:12:37 GMT 2016'
  ++ pwd
  + Start_Directory=/home/pi
  ++ pwd
  + Working_Directory=/home/pi/Arduino/build
  + echo -e '\n\nChecking for root .. \n'

  Checking for root ..

  ++ id -u
  + '[' 0 '!=' 0 ']'
  + echo 'Yuppers .. :)~'
  Yuppers .. :)~
  + [[ yes == \y\e\s ]]
  + echo -e '\n\nChecking to see if I'\''m update\n'

  Checking to see if I'm update

  git remote update
  fatal: Not a git repository (or any of the parent directories): .git


texts: I am having trouble getting my Arduino uno to run my code when I disconnect it from my computer. I have a 9V battery to power it and it is turning on, however, it is not doing anything at all. What can I do to make it run the code when it is using the battery and not connected to the computer?


texts: Problems with Windows 8.1 install of Arduino IDE

texts:
I have replaced my Arduino, thinking it would solve the problem, but I still get it. Whenever I try to upload code, I get the error messages programmer is not responding and not in sync. Then I heard Arduino had drivers required. But my Windows 8.1 didn't recognize Arduino Uno. It was put in the other devices area as an unknown device in the device manager. The update driver button is greyed out. I get the message:

  The drivers for this device are not installed (code 28). There are no
  compatible drivers for this device. To find a driver for this device,
  click update driver.

That's the greyed out button… When I look at driver details, it says 'No driver files are required or have been loaded for this device.' For the not in sync/programmer not responding error, I've tried restarting the board before uploading, restarting whilst uploading, you say it, I've done it. How can I fix this so I can finally follow my dream to be an engineer/programmer?


texts: How to increase the serial port's data throughput

texts:
I have an array of numbers that will be subtracted from the ADC readings
of a 50 Hz sine wave. Using Serial.begin(57600);, I can only
output 25 samples per sine wave cycle, or about 1,250 samples per
second. my questions are:

how fast the increent of array number moves with y++ in my int sinus[]? because when i see on serial monitor with 52700 baudrate it can only show about 25 numbers per cycle (50Hz)
how to increase the speed the increment of y++ in my array?

int sinus[] = {
    70, 72, 83, 92, 108, 132, 157, 182, 207, 230, 243, 255, 255,
    255, 250, 238, 217, 193, 169, 143, 118, 98, 88, 77, 72, 80
};
int dataSensor;
int hasil[26];
int datasensor2;
int dataBaru;
int x;
int y;
int intPin = 2;
int output;
int output2;
int toggle;
int toggle2;
int z;

void setup() {
    TCCR1A = 0b00000010;
    TCCR1B = 0b00011100;
    TCCR0A = 0;  //disable millis, delay and mciros
    TCCR0B = 0;
    ICR1 = 3200;

    Serial.begin(57600);

    pinMode(A1, INPUT);
    pinMode(A0, INPUT);
    pinMode(A2, INPUT);
    pinMode(intPin, INPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);

    attachInterrupt(0, genJeah, RISING);
}

void genJeah() {  //intrupsi rising
    y = 5;
}

void loop() {
    dataSensor = analogRead(A0);
    toggle     = digitalRead(A1);
    toggle2    = digitalRead(A2);
    dataBaru = map(dataSensor, 0, 1023, 0, 255);

    for (x = 0; x < 25; x++) {
        hasil[x] = sinus[x];
    }
    // for (x=0; x<100; x++){

    output = sinus[y] - dataBaru;
    Serial.println(output);
    y++;
    if (y > hasil[26]) {
        y = 0;
    }
}


texts: Cannot read from 2 I2C slaves consecutively

texts:
I am currently trying to communicate between 3 Arduinos using I2C. One of them acts as a master, while the rest act as slaves.

I can request data correctly from the master. But if I were to do 2 consecutive requests, I will only get data for the last request. Please assist.

Master:

#include <Wire.h>

#define BLUNO_SLAVE 0x09
#define BLUNO_SLAVE_2 0X0A

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Serial.println("Initialized as Master");
  Serial.println("Reading from slave 1 now..");
  //Wire.beginTransmission(BLUNO_SLAVE);
  Wire.requestFrom(BLUNO_SLAVE, 25);  //char occupy 1 byte
  //Wire.endTransmission();
  Serial.println("Reading from slave 2 now..");
  Wire.requestFrom(BLUNO_SLAVE_2, 30);
}

void loop () {
  while(Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }
}

Slave 1:

#include <Wire.h>

void setup() {
  Serial.begin(115200);
  Wire.begin(0x09);  //slave address
  Serial.println("Serials initialized");
}

void loop() {
  Wire.onRequest(returnData);
}

void returnData() {
  Wire.write("received master's request");
}

Slave 2:

#include <Wire.h>

void setup() {
  Serial.begin(115200);
  Wire.begin(0x0A);  //slave address
  Serial.println("initialized!");
}

void loop() {
  Wire.onRequest(returnData);
}

void returnData() {
  delay(60000);  //60 * 1000 = 60 seconds
  Wire.write("Lat: 103.123456, Lon: 1.098765");
}

Output on the master:

Initialized as Master
Reading from slave 1 now..
Reading from slave 2 now..
Lat: 103.123456, Lon: 1.098765

On top of that, I do not understand why the 1 minute delay was not executed before the slaves write the GPS coordinates.

I figured out from http://playground.arduino.cc/Main/WireLibraryDetailedReference
that each call to the requestFrom() method, RESETS the read buffer. I looked at my code back and I saw a silly mistake on the master code. So, I corrected the master code:

#include <Wire.h>

#define BLUNO_SLAVE 0x09
#define BLUNO_SLAVE_2 0X0A

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Serial.println("Initialized as Master");
  Serial.print("Slave 1: ");
  Wire.requestFrom(BLUNO_SLAVE, 25);  //char occupy 1 byte
  readData();
  //each call to requestFrom, RESETs the read buffer index
  Serial.println();
  Serial.print("Slave 2: ");
  Wire.requestFrom(BLUNO_SLAVE_2, 30);
  readData();
}

void loop () {
}

void readData () {
  while(Wire.available()) {
  char c = Wire.read();
  Serial.print(c);
 }
}

But still, I don't understand why slave2 writes the data immediately instead of waiting for 1 minute?


texts: Unable to set LCD contrast using DAC pin on ESP32

texts:
I have followed the instructions at https://www.arduino.cc/en/Tutorial/HelloWorld and have my LCD displaying some text. I've also connected the LED back light (LCD pins 15&16).

I wanted to replace the potentiometer used to set the contrast, with a connection to the DAC pin. It needs to be about 0.8V.

When I connect the contrast pin from the LCD to my DAC pin on my ESP32 board, it doesn't work, the contrast is too high. Using a volt meter, it measures about 2.5V.

If I disconnect the LCD contrast pin from my DAC pin, the voltage measured is 0.8V.

Any ideas or examples on how to control the LCD contrast using a DAC pin?

I wondered if I need to add a resistor or something.


texts: Is there a module that will allow me to pair a bluetooth keyboard to an arduino?

texts:
I want to pair a bluetooth keyboard to an arduino project, so that pressing a key on the keyboard causes an action to happen on the Arduino. Let's say that pressing Q on the keyboard makes an LED turn on, and pressing W makes it turn off.

I know that I need some sort of bluetooth module connected to the Arduino, and I need to pair the keyboard to the module. I also know that it must be a module that can act in Master mode and use the HID protocol. But I cannot find a module that does what I want. For example, the HC05 module cannot do HID.

Has anyone done this? Can you tell me which module you used please? I don't want to involve anything else, just an Arduino, a module, and a bluetooth keyboard.


texts: Using Arduino RS232 to a modem (only RS232)

texts:
I am a newbie to the arduino world. And am trying to work out a configuration that does not involve USB.

I wonder if this configuration will work.

Are there any 3g modems that work on Rs232 interface. That should get rid of the USB compatibility that costs 3 times a arduino.


texts: How to make a custom character on a TFT LCD display? (128x128)

texts:
I'm currently using the ucglib library. I'm new to arduino and I'm wanting to simply display a lcd smiley I made with the byte generator. I still have some of the original 'font hello world' stuff down the bottom but I'm curious how to make my character work.

I want to make different smileys in different colours but I'm unsure how to go about this as every guide is on a 16x2 lcd and not a tft one. I have an arduino nano that is just hooked up to that lcd display. I'm going to make pressing buttons change the smiley after I've figured out how to actually put a smiley into it. Hope someone can help.

 * LED =   3.3V
 * SCK =   13
 * SDA =   11
 * A0 =    8
 * RESET = 9
 * CS =    10
 * GND =   GND
 * VCC =   5V

    #include "Ucglib.h"  // Include Ucglib library to drive the display

// Create display and define the pins:
Ucglib_ST7735_18x128x160_HWSPI ucg(8, 10, 9);

int smiley = byte customChar[] = {
  B00000,
  B01010,
  B01010,
  B00000,
  B10001,
  B10001,
  B11111,
  B00000
};

void setup(void)  // Start of setup
{

  //ucg.begin(UCG_FONT_MODE_TRANSPARENT);  // It doesn't overwrite background, so it's a mess for text that changes
  ucg.begin(UCG_FONT_MODE_SOLID);  // It writes a background for the text. This is the recommended option

  ucg.clearScreen();  // Clear the screen

  ucg.setRotate180();  // Put 90, 180 or 270, or comment to leave default

  ucg.setColor(0, 255, 255, 255);  // Set color (0,R,G,B)
  ucg.setColor(1, 0, 0, 0);  // Set color of text background (1,R,G,B)
  ucg.setPrintPos(0,24);  // Set position (x,y)
  ucg.print("Welcome");  // Print text or value

  // Draw smiley:
  ucg.setColor(0, 255, 255);  // Set color (0,R,G,B)
  ucg.drawFrame(0, 58, 60, 30);  // Start from top-left pixel (x,y,wigth,height)

void loop(void)  // Start of loop
{

  Variable1++;  // Increase variable by 1
  if(Variable1 > 150)  // If Variable1 is greater than 150
  {
    Variable1 = 0;  // Set Variable1 to 0
  }

  // Convert Variable1 into a string, so we can change the text alignment to the right:
  // It can be also used to add or remove decimal numbers.
  char string[10];  // Create a character array of 10 characters
  // Convert float to a string:
  dtostrf(Variable1, 3, 0, string);  // (<variable>,<amount of digits we are going to use>,<amount of decimal digits>,<string name>)

  // We are going to print on the display everything that is dynamic on the loop, to refresh continuously:

  // Write to the display the Variable1 with left text alignment:
  ucg.setFont(ucg_font_inb16_mr);  // Set font
  ucg.setColor(0, 255, 255, 0);  // Set color (0,R,G,B)
  ucg.setColor(1, 0, 0, 0);  // Set color of text background (1,R,G,B)
  ucg.setPrintPos(9,81);  // Set position (x,y)
  ucg.print(Variable1);  // Print text or value

  // There is a problem when we go, for example, from 100 to 99 because it doesn't automatically write a background on
  // the last digit we are not longer refreshing. We need to check how many digits are and fill the space remaining.
  if(Variable1 < 10)  // If Variable1 is less than 10...
  {
    // Fill the other digit with background color:
    ucg.print(" ");
  }
  if(Variable1 < 100)  // If Variable1 is less than 100...
  {
    // Fill the other digit with background color:
    ucg.print(" ");
  }

  // Write to the display the string with right text alignment:
  ucg.setFont(ucg_font_inb16_mr);  // Set font
  ucg.setColor(0, 0, 255, 0);  // Set color (0,R,G,B)
  ucg.setColor(1, 0, 0, 0);  // Set color of text background (1,R,G,B)
  ucg.setPrintPos(76,81);  // Set position (x,y)
  ucg.print(string);  // Print text or value

}  // End of loop


texts: Voltage issue on an esp32 wvroom 32D development board

texts:
I have an esp32 wroom 32 dev board. I'm running into power issues and I'm not sure what's going on.

When I try to upload sketches the uploads fail if I have any jumpers running to the 5v or 3.3v pins which is weird.

Also, when I have nothing plugged into the board other than the usb cable and try to measure voltage across the ground and power pins I get 1.5v from the 5v pin and 0 from the 3.3 pin

This is a brand new out-of-the-static-bag board and I'm having the same issue with another board of the same type.

I feel like there's something I'm missing. Any ideas?


texts:
I recently bought a 5050 RGB 12V 3A LED strip and I set it all up with my Arduino and run this code (from adafruit website), everything is good:
Example Code
Once you have the strip wired up, it is easy to control the color of the strip by using PWM output, for Arduino you can use

#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3

#define FADESPEED 5     // make this higher to slow down

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);
}

void loop() {
  int r, g, b;

  // fade from blue to violet
  for (r = 0; r < 256; r++) {
    analogWrite(REDPIN, r);
    delay(FADESPEED);
  }
  // fade from violet to red
  for (b = 255; b > 0; b--) {
    analogWrite(BLUEPIN, b);
    delay(FADESPEED);
  }
  // fade from red to yellow
  for (g = 0; g < 256; g++) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }
  // fade from yellow to green
  for (r = 255; r > 0; r--) {
    analogWrite(REDPIN, r);
    delay(FADESPEED);
  }
  // fade from green to teal
  for (b = 0; b < 256; b++) {
    analogWrite(BLUEPIN, b);
    delay(FADESPEED);
  }
  // fade from teal to blue
  for (g = 255; g > 0; g--) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }
}

I tried to find a way to achieve the same effect but only with two colors...red to yellow..red fade to yellow and fade to red and so on..

EDIT:
Thanks to @majenko I achieved this...Fade from Red to Yellow and back on:

    for (int r = 0; r < 256; r++) {
        analogWrite(REDPIN, r);
        analogWrite(GREENPINPIN, 255 - r);
        analogWrite(BLUEPIN, 0);
        delay(FADESPEED);
    }

    // Fade red down and blue up
      for (g = 0; g < 256; g++) {
        analogWrite(REDPIN, 255);
        analogWrite(BLUEPIN, 0);
        analogWrite(GREENPINPIN, G);
        delay(FADESPEED);
      }


texts: Should long wires be kept separated from each other, to reduce interference?

texts:
Let's say someone has four CAT5 cables that are running along the ceiling for the length of a room (30 feet), of which most of the twisted pairs are connected to Arduino input/output pins on one end. Would it be okay to keep these wires bundled together when running along the ceiling? Or is it safer to keep them separated by a few inches? Is interference usually a problem only in very specific situations, or should it be considered for all long wire runs?

How about if there is a telephone cable (hooked up to a landline telephone) running along the same length? Is there any chance of interference if this is too close to the Arduino cables?

How about if there are 120v mains lines running the same length? Should these be kept at a distance from the Arduino cables?

On the other end of the cables that are hooked up to the Arduino, some of the following are connected: temperature sensors, light sensors, servo motors, LCDs, relays, and push-buttons.


texts: Sending values to an Arduino Yun across different networks

texts: I have quite a lot of experience with Arduino but have recently been faced with a challenge that has stumped me. The project is to create a robot that can be controlled from a separate network than it is on. I had the idea of using the Yun board to receive the values. Does anyone know a way I could have a computer send data to a Yun on a different network? (Maybe through a website?)


texts: Cannot create a PWM with 20% duty cycle using micro() timer

texts:
I have been working with Arduino for almost a year, because I found it easy for beginners in electronics. But now, I have a major problem, I'm trying to get rid of my delay() function because I want my Arduino Nano to handle to tasks at once:

1-Read MIDI data and transfert it into a pwm signal, as well as monitoring the on and off of the signal (which are bytes). This part works correctly, but i'm not using the mirco(), i'm using a library called Timer1.

2-Generate a PWM signal of 20% dutycycle with a frequency ranging from 1 to 103 Hz using a potentiometer to adjust the frequency.

So, what happens is that the signal I measure on my oscilloscope is a PWM at 50% duty cycle and with frequencies that don't match my calculations at all. Also, It doesn't change smoothly, the frequency goes from 159Hz to let's say 180Hz only at one particular point on the potentiometer, just like if all the rest of it was useless. I decided to monitor all my values with Serial and everything was good, the values were OK and nothing was wrong. Then I decided to change all my variables to floats so I could maybe get more precision... Didn't work as well. So now I'm kind of desesperate.

//MANUAL MODE TEST WITH MICROS()
//VARIABLES ASSIGNEMENT
unsigned long current=0.0;
unsigned long previous=0.0;

float TimeOn = 0.0;
float TimeOff = 0.0;
float manuelF = 0.0;
float sensor = 0.0;

int pin = 11;

byte state = LOW;

//SETUP AND PIN ASSIGNEMENT
void setup() {
  pinMode(9, OUTPUT);//MUSIC SIGNAL OUTPUT
  pinMode(11, OUTPUT);//MANUAL SIGNAL OUTPUT
  pinMode(A5, INPUT);//POTENTIOMETER MANUAL
  pinMode(A6, INPUT);//POTENTIOMETER MUSIC
  Serial.begin(9600);
}

void loop() {

  sensor = analogRead(A5);
  manuelF=((sensor+10.0)/10.0); //Capture la fréquence sur A5
  TimeOn=1000000.0*(0.2*(1.0/manuelF));
  TimeOff=1000000.0*(0.8*(1.0/manuelF));
  current = micros();

  Serial.println(TimeOn);

  //Serial.print("A5 read:");
  //Serial.println(analogRead(A5),8);
  //Serial.println("-----------");
  //Serial.print("Fréquence: ");
  //Serial.println(manuelF,8);
  //Serial.print("timeon:");
  //Serial.println(TimeOn,8);
  //Serial.print("timeoff:");
  //Serial.println(TimeOff,8);

  if ((state == LOW)&&(current - previous >= TimeOff)){
      state = HIGH;
      digitalWrite(pin,state);
      previous = current;
    }
  else{
    if (current - previous >= TimeOn){
      state = LOW;
      digitalWrite(pin,state);
      previous =current;
    }

  }
 }

As you can see I'm still monitoring the TimeOn variable. Well, It shows exactly (to 4 micro seconds precise) the time that it is supposed to be ON.

My output at that moment is a 50% duty cycle with a frequency of 53Hz when I pass the 7k on the potentiometer (it is a 10k). Before that, it doesn't even outputs a signal.

What is going on?

EDIT#1:
I have done the modifications that @Edgar Bonet suggested me. It partially worked. What i'm left with now is a PWM that can go from 1Hz to 5Hz almost smoothly with the duty cycle at 20% for 1Hz and going up to 22% at 5Hz. After that I only get very discrete frequencies: 7.99Hz, 9.55Hz, 10.66Hz, 11.99Hz, 13.70Hz, 19.18Hz, 21.32Hz, 26.65Hz, 35.54Hz and then it takes almost half a turn before it changes to 53.3Hz until the end. The duty cycle at 35Hz is 33.3% and it reaches 50% at 53.3Hz... What logic is that....


texts: May arduino hang when current is changing over time?

texts: As in title. I've got quadrocopter where Li-Po is parallely connected to motors as well as to arduino. May current driftage cause arduino hangs ?


texts: Does baud rate for HC-05 Bluetooth module need to match the Serial Monitor?

texts:
I have this sketch that I got as a sample.  I have the two HC-05s connected.  What I type in one serial monitor shows up on the other, but as question marks.  The most common reason for this I find is baud rate doesn't match.   I didn't change the baud rate on the HC-05s when I got them, so I assume they are set to default.  I can put them in command mode and ensure the baud rate is set.

Does the baud rate of the HC-05s have to match the baud rate of the Serial monitor?  I would assume not.  I am also wondering if this is a problem with formatting a char[] when writing to the serial display.

#include <SoftwareSerial.h>
SoftwareSerial BTserial(7, 8); // RX | TX
// Connect the HC-05 TX to Arduino pin 7 RX.
// Connect the HC-05 RX to Arduino pin  8 TX through a voltage divider.
//

char c = ' ';

void setup()
{
Serial.begin(9600);
Serial.println("Arduino is ready");
Serial.println("Remember to select Both NL & CR in the serial monitor");

// HC-05 default serial speed for AT mode is 38400
BTserial.begin(38400);
}

void loop()
{

// Keep reading from HC-05 and send to Arduino Serial Monitor
if (BTserial.available())
{
    c = BTserial.read();
    Serial.println(c);
}

// Keep reading from Arduino Serial Monitor and send to HC-05
if (Serial.available())
{
    c =  Serial.read();
    BTserial.write(c);
}
}


texts: I am pretty new to arduino.I am working on a project which requires comparison of two keypad inputs to operate a relay using arduino. I have found lot of info on connecting single keypad but none about connecting two keypad inputs.So how can i connect two keypad and a relay to arduino?Thanx in advance.


texts: Arduino uno and Nano as master and slave

texts:
please help me!!
I'm using two arduino (uno and Nano) as master and slave. I wants to control 3 servo which are connected  on Nano (slave) by uno (master). Uno  have 3 push buttons on it to control all 3 servos connected on Nano. But I couldn't make a good working program for it.. Please help me to make a program for it. I'm using TX and RX pins for it. Thank you.
I have added a photo, please consider it that push buttons are connected to + 5v and GND to 470 ohms resistor and arduino ground. Please help me !

Code for master -

const int Button_1 = 2;
const int Button_2 = 4;
int s = 0;
void setup ()
{
    Serial.begin(115200);
    pinMode (Button_1,INPUT);
    pinMode(Button_2,INPUT);
}
void loop()
{
    if(digitalRead(Button_1))
    {
        s=2;
        Serial.print(s);
        delay (5);
        s=0;
    }
    else
    {
        s=1;
        Serial.print(s);
        delay (5);
        s=0;
    }
    if(digitalRead(Button_2))
    {
        s=4;
        Serial.print(s);
        delay (5);
        s=0;
    }
    else
    {
        s=3;
        Serial.print(s);
        delay (5);
        s=0;
    }
}

For slave -

#include <Servo.h>
Servo servo_1;
Servo servo_2;
int r=0,p=0;
void setup()
{
    Serial.begin(115200);
    servo_1.attach(3);
    servo_2.attach(5);
}
void loop()
{
    if(Serial.available()>0)
    {
        r=Serial.read()-'0';
        if(r==2)         // for servo 1
        {
            for(;p<=180;p++)
            {
                servo_1.write(p);
                delay(5);
                if (Serial.read()-'0'==1)
                break;
            }
            r=0;
        }
        if(r==1)
        {
            for(;p>=0;p--)
            {
                servo_1.write(p);
                delay(5);
                if (Serial.read()-'0'==2)
                break;
            }
            r=0;
        }
    if(r==4)         // for servo 2
        {
            for(;p<=180;p++)
            {
                servo_2.write(p);
                delay(5);
                if (Serial.read()-'0'==3)
                break;
            }
            r=0;
        }
        if(r==3)
        {
            for(;p>=0;p--)
            {
                servo_2.write(p);
                delay(5);
                if (Serial.read()-'0'==4)
                break;
            }
            r=0;
        }
    }
}


texts:
I'm trying to have a common light switch turn a LED on and off.

When I connect the light switch directly to a LED, it works like it should - the LED turns on and off with the switch.

When I connect the light switch back to the board, changing the switch does nothing - I get the exact same signals regardless of whether the switch is on or off.

Why?
How do I make the board recognize whether the switch is on or off?

The diagram I followed:

const int  buttonPin = 2;

const int ledUt = 13;
const int ledTest = 12;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;

int tilstand = 0;

int buttonStateForrigeForrige = 0;

boolean light = false;

void setup() {
  Serial.println("Hello World");
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
  pinMode(ledUt, OUTPUT);
  pinMode(ledTest, OUTPUT);

}

void loop() {

  digitalWrite(ledTest, HIGH);
  buttonState = digitalRead(buttonPin);
  Serial.println("Sjekk");

  tilstand = LOW;
  if ( buttonState == HIGH ) {
    Serial.println("buttonState HIGH");
    if ( lastButtonState == HIGH ) {
      Serial.println("lastButtonState HIGH");
      tilstand = HIGH;
    } else {
      Serial.println("lastButtonState LOW");
    }
  } else {
    Serial.println("buttonState LOW");
  }

  if (buttonState != lastButtonState) {

    if (buttonState == HIGH) {
      buttonPushCounter++;
      Serial.println("on");
      Serial.println(buttonPushCounter);
    } else {
      Serial.println("off");
    }
  }
  buttonStateForrigeForrige = lastButtonState;
  lastButtonState = buttonState;

  if (tilstand == HIGH) {
    digitalWrite(ledUt, HIGH);
  } else {
    digitalWrite(ledUt, LOW);
  }
  }


texts: Pin Mapping of nRF2401L01+ using Adafruit's nRF24L01+ library

texts:
I have an Arduino Uno and one of these nRF24L01+ from china (see image)

To use the module i wanted to use the library provided by Adafruit (http://playground.arduino.cc/InterfacingWithHardware/Nrf2401). My problem is, that they're using different names for some pins, because the library is designed for a different module with the following pin outs.

I don't know which PIN from the China module corresponds to the DAT and DR1 Pin on the Adafruit module.

So my questions are:

Is it OK to use the library in conjunction with the china module?
What are the DAT and DR1 PIN on the module from China ?

What I know so far:
- took a look into the library and into the documentation at playground.arduino.cc/InterfacingWithHardware/Nrf2401 and found out that the DR1 pin is for the available() function to check if data is available to be read.


texts:
Some of the code that I have is unbearably long and drives me insane. I don't know if there were simpler ways to doing what I am doing.

long turn1;
long turn2;
long turn3;
long turn4;
long turn5;
long turn6;
long turn7;
long turn8;
long turn9;
long turn10;
long turn11;
long turn12;
long turn13;
long turn14;
long turn15;

#################

  turn1 = random(sizeof(turns) / sizeof(char*));
  turn2 = random(sizeof(turns) / sizeof(char*));
  turn3 = random(sizeof(turns) / sizeof(char*));
  turn4 = random(sizeof(turns) / sizeof(char*));
  turn5 = random(sizeof(turns) / sizeof(char*));
  turn6 = random(sizeof(turns) / sizeof(char*));
  turn7 = random(sizeof(turns) / sizeof(char*));
  turn8 = random(sizeof(turns) / sizeof(char*));
  turn9 = random(sizeof(turns) / sizeof(char*));
  turn10 = random(sizeof(turns) / sizeof(char*));
  turn11 = random(sizeof(turns) / sizeof(char*));
  turn12 = random(sizeof(turns) / sizeof(char*));
  turn13 = random(sizeof(turns) / sizeof(char*));
  turn14 = random(sizeof(turns) / sizeof(char*));
  turn15 = random(sizeof(turns) / sizeof(char*));

#

if (turn1 == turn2 or turn2 == turn3 or turn3 == turn4 or turn4 == turn5 or turn6 == turn7 or turn7 == turn8 or turn8 == turn9 or turn9 == turn10 or turn10 == turn11 or turn11 == turn12 or turn12 == turn13 or turn13 == turn14 or turn14 == turn15) {

#

lcd.print(turns[turn1]);
lcd.print(turns[turn2]);
lcd.print(turns[turn3]);
lcd.print(turns[turn4]);
lcd.print(turns[turn5]);
lcd.setCursor(0, 2);
lcd.print(turns[turn6]);
lcd.print(turns[turn7]);
lcd.print(turns[turn8]);
lcd.print(turns[turn9]);
lcd.print(turns[turn10]);
lcd.setCursor(0, 3);
lcd.print(turns[turn11]);
lcd.print(turns[turn12]);
lcd.print(turns[turn13]);
lcd.print(turns[turn14]);
lcd.print(turns[turn15]);


texts: Why would the resistor be after the LED in this project?

texts: This is project 2 of their official arduino projects book called "Spaceship interface". I understand resistors normally reduce voltage so the LEDs don't burnout but here 5v is coming from either digital 3, 4, or 5 and it seems like it goes right into the LED before going through a resistor as it goes back to ground. This makes no sense to me.


texts: Find external router IP from Arduino Yun inside router network

texts:
I want two Arduino Yuns in different private networks to communicate, i.e., behind two distinct routers of which at least one does not have dynamic DNS, so its external IP may change from time to time.

To be reachable, this Yun could forward its router's external IP to the other Yun which has a fixed DNS name. But for this to work, it must be able to determine its router's external IP.

How can the Yun find out that the external IP of the router has changed? The Yun will be runnning all the time.
If the external router IP has changed (i.e., my Fritz.Box disconnects in the night and may receive a different IP when it reconnects), how can the Yun determine the new external IP?

If this is not the right place to ask, I'm happy for pointers to somewhere else (Server Fault SE forum?).


texts: Reverse DC motor direction every second automatically

texts:
I have the Arduino Starter Kit and I'm on project 10 Zoetrope. I've removed the switch that changes the direction as I don't want the reverse to happen when I press a switch. I want the reverse to happen based on time.

For example using code, I want the reverse to happen every second (the motor moves clockwise for the first second, counterclockwise for the next second, clockwise for the third second etc.)

I've search for solutions but I haven't found anything yet. I had no luck with the millis function as well.


texts:
I'm trying to set my temperature measurements to two decimal places. Currently what I get are six decimal places.
Here is my code:
#include "math.h"

...

(in loop)
temp1 = sensors.getTempCByIndex(0);
     temp1 = roundf(temp1*100)/100;

Once I push temp1 to Firebase realtime database there are sic decimals, such as 26.059999. I'm using dsb20 sensor for temperature measurements.
What could be wrong?
Thanks for your help in advance!


texts: Arduino server to read from multiple clients

texts:
Socket programming question here.

My interface comprises of an Android device(client), A wireless module hosting an access point, and an Arduino Uno(server).

My Android client class works when 1 user connects and sends commands to my Arduino server class.

I want to make my program friendly to many users at the same time.  My server will only read in values from 1 connected client at a time.

After some research I've found that Arduino does not allow multithreading naturally, which is why i've decided to look into a number of libraries.

The Arduino library that I've decided to use for this specific issue is protothreads.  Unfortunately, i've been unable to find any examples of creating a server with Arduino to accept a client's commands.  Furthermore I'm having a lot of trouble figuring out how to make this library work in my favor.

Now for my question,

  How exactly can I allow my Arduino server to constantly listen for
  incoming messages from more than 1 client device?

Or is there something I can do on the client side that would make this communication possible?

A lot of work is handled by my Wifly Module.
I was able to telnet in and set my ipaddress/port#/etc..
Anything sent over IP goes straight through my Module and straight to my arduino.

My
Client Code:

My Server:

WiFlySerial wifi(rxPin ,txPin);

void setup() {
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  pinMode(led, OUTPUT);
}

void loop() {
  //Serial.println("I'm in the LOOP!!");
  androidLed();
  serialLed();

}

void androidLed()
{
  if(wifi.available() > 0){
    data = wifi.read();
    Serial.println(wifi.getDeviceStatus());
    Serial.println(data);
}
}


texts:
I'm trying to gain an understanding of the Arduino timer and interrupts, particularly the CTC-modes 4 and 12. I wrote a small example in which I generate interrupts while the mainloop sleeps for 1 second and the display how many interrupts occured. It can toggle between mode 4 and 12 with the #if 1.

This works fine for mode 12 ( 50 interrupts/sec ) but in mode 4 it gives -12k interrupts / seconds... unless when I set OCR1A to 39999 again inside the ISR then it does give the expected 50 interrupts/sec, but I'd like to know why.

I think my confusion might be related to not understanding the table-header explaining the modes where it says "Update of OCR1x at". What is meant with that ( who updates it, and to what value? or do I need to update it in the ISR ) ?
Why would OCR1x be updated in mode 12 ( the table seems to state that it is) ? And it seems to work, even if I don't update it...?

Also, the only difference between mode 4 and 12 seems to be the register used for comparing to the timervalue (OCR1A vs ICR1)... but what is so fundamentally different between those? Why are there 2 options and what is the argument to choose for either mode 4 or 12 ?

Update: The issue seems to be related to initialization-order. If OCR1A is set to 39999 at the current location it gets reset to 0 a few lines further. When moving it after TCCR1A = TCCR1B = 0; then OCR1A keeps the value. So it's not necessary to set it on every interrupt.
This also explains why we get -12k counts on mode 4 (because we are comparing OCR1A in that mode, comparing to 0 and generating loads of interrupts)...

Any insight into why the initialization-order matters in this case would be appreciated.

Thanks in advance!

volatile int isr1 = 0;

ISR(TIMER1_COMPA_vect)
{
  // this is called every time our timer-compare matches to ICR1 or OCR1A
  isr1++;

  // when using the #if part below, we need to do this, or we end up with weird values for isr1 ( around -12.000 )
  // If we set it to the original value then we get 50 interrupts per second...
  OCR1A= 39999;
}

void setup() {

  Serial.begin(115200);
  delay(50);

  ICR1 = 39999;                   // 50Hz signal @ 16MHz clock
  OCR1A= 39999;

//TIMSK1 |= 1 << ICIE;            // bit 5: Input Capture Interrupt Enable (execute interrupt when TIFR1.ICF flag is set)
  TIMSK1 |= 1 << OCIE1A;          // bit 4 : Enable the Timer-Output-CompareA-Match Interrupt

  TCCR1A = TCCR1B = 0;            // reset timer-config flags
   // An interrupt can be generated at each time the counter value reaches the TOP value by either using the OCF1A or ICF1 Flag,
   // depending on the actual CTC mode. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value.
#if 1
  // Arduino Datasheet 20.12.2. : The counter value (TCNT1) increases until a compare match occurs with OCR1A, and then TCNT1 is cleared.
  TCCR1B |= 1<<WGM12;             // code 4 (CTC, compare with OCR1A, Immediate update of OCR1x, overflow on MAX)
#else
  // Arduino Datasheet 20.12.2. : The counter value (TCNT1) increases until a compare match occurs with ICR1, and then TCNT1 is cleared.
  TCCR1B |= 1<<WGM13 | 1<<WGM12;  // code 12 (CTC, compare with ICR1, Immediate update of OCR1x(?), overflow on MAX)
#endif

  // using a prescaler of 8, which "slows down" the clockticks by factor 8.
  // 1 clocktick takes 0.5 microseconds, so 39999 clockticks need 19999,5 microseconds
  // 1 second = 1.000.000 microseconds, so we get 50 interrupts per second
  TCCR1B |= 1<<CS11;   // timer CS11 = clki/o/8, 1 tick per 0.5 microseconds
}

void loop()
{
  delay(1000);            // wait 1 second
  Serial.println(isr1);   // print how many interrupts we had in that second
  isr1 = 0;               // and reset for the next second.
}


texts: Is it possible to use FrSky D8R-II Plus 8ch 2.4Ghz ACCST Receiver with an arduino Uno?

texts:
I'm in the process of buying a receiver and transmitter for my quad copter project. Would it be possible to use this receiver or a similar one to control the quad. I'm trying to read the signals using Pulse in. I'm inexperienced in RC and I only found one tutorial on how to do this.

I know that the receiver will have to be wired up to the analog pins on the arduino however, the receiver has an operating voltage of 3.5V-10V and an operating current of 100mA which exceeds the 40mA of the arduino board. I have seen videos of people using silar 2.4Ghz receivers on arduino Nanos without problems. Has anyone on this board done something similar and if so, can thou guide me?


texts: What are the benfits of global variables over static class members?

texts:
On an embedded system we use global variables often to keep dynamic memory consumption on heap and stack low. But global variables are also considered bad programming practice if they aren't used in a global sense, i.e. they are used only inside one or two functions.

So I really want to make use of the possibilites to protect my code from myself. Of course, the instantiation mechanism of c++ is to avoid on an embedded system with low resources, like an arduino. So I write classes with static members (and member functions) only. Many of the libraries shipped with arduino seem to work this way, too.

I'm curious if there's a single drawback of moving static variables or even const arrays (designed for deposit in progmem) from global namespace to a class namespace and making them private?

I'm primarily interested in drawbacks arising from the combination of OOP with the arduino platform (using an arduino uno) with avr-gcc.


texts:
I installed the Arduino IDE according to the arduino.cc instructions (invoking install.sh) rather than sudo apt install .... The ports /dev/ttyACM* were present when the following Linux command is issued.

ls -l /dev/ttyACM*

This shows that the devices have membership in the dialout group. It is necessary to add myself as a user to the group dialout.

sudo usermod -a -G dialout <username>

I selected the board and the port and did a download which eventually completed but it seemed to take a long time. The program probably wasn't working since the program was to flash an LED at a 2 second period but the flash rate was definitely much faster so it seems the download did not work.

I deleted the IDE and reinstalled and the ports disappeared.

I have applied this fix for using the Arduino IDE on Linux.

From the description of the fix the instruction is to issue the following commands:

wget https://github.com/adafruit/Trinket_Arduino_Linux/raw/master/99-adafruit-boards.rules

sudo cp 99-adafruit-boards.rules /etc/udev/rules.d/

Next reboot Linux.

According to this page on Arduino for Linux there ought to be some devices at /dev/ttyACM* but mine are missing. What is the solution to this problem? I have replaced the USB cable and it makes no difference.

The board is Adafruit Feather 32u4 which has an ATmega32u4. The OS is Ubuntu 16.04.


texts: Why does this scope-based timer not work as intended?

texts:
I wrote the following scope-based timer to help me profile my code and improve its efficency, but in testing I found that it reports durations far shorter than it should:

class CodeTimer {
 public:
  CodeTimer(const String& name) : _name(name) {
    Serial.println("Begin execution of \"" + _name + "\".");
    _begin = micros();
  }

  ~CodeTimer() {
    unsigned long duration = micros() - _begin;
    Serial.println("\"" + _name + "\" execution took " + duration + "µs.");
  }

 private:
  unsigned long _begin;
  String _name;
};

For example, I'd use it like so in my sketch:

void setup() {}

void loop() {
  CodeTimer("void loop()");
  int begin = millis();

  delay(100); // Simulation of work that takes 100ms.
  Serial.println(millis() - begin);
}

Then, when I go to run the above sketch on my Blue Pill board (STM32F103C8), I get something like this printed to the terminal:

Begin execution of "void loop()".
"void loop()" execution took 4µs.
100
Begin execution of "void loop()".
"void loop()" execution took 3µs.
101
Begin execution of "void loop()".
"void loop()" execution took 4µs.
100

Something is very wrong with when the destructor to CodeTimer is being called, and I'm not exactly sure what it is.


texts: Limiting motors to a specific position using while and if loops

texts:
I am currently building a prosthetic hand using an Arduino MEGA, an Advancer Tech Myoware sensor, and 3 TB6612FNG Dual H-bridge breakouts. I have the EMG sensor sending an analog value to the Arduino and want to use that value to open or close the hand.

The problem I have is that the motors cannot turn more than 1 second without tightening too much and breaking the hand, so I want to place a limit on the while loop telling them to move that will restrict their movement under the specified conditions to one second. Also, when the analog voltage is no longer present, I need the motors to reverse their movement so the hand releases.

Here is the code I have where move(motor #, speed, direction) is the function to move the hand (1 = forward, 2 = backward).

void loop(){

  int EMGv = analogRead(EMG);

  while(EMGv >= 900){
    move(0, 255, 1); //motor 1, full speed, left
    move(1, 255, 1); //motor 2, full speed, left
    move(2, 255, 1); //motor 3, full speed, left
    move(3, 255, 1); //motor 4, full speed, left
    move(4, 255, 1); //motor 5, full speed, left

  }

To reiterate. I need the motors to move while the EMG value is over 900, BUT not move more than 1 second, even if the value is 900 for 5 seconds. I then need the motors to move one second backwards when the value dips below 900.

Thanks!


texts:
I used this example code:

#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
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 );

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

void loop(){
  char key = keypad.getKey();

  if (key != NO_KEY){
    Serial.println(key);
  }
}

And when I upload it to my Arduino and start the Serial Monitor, it prints a 1 and that's it. No other output if I press the keys. I have a 4x4 Keypad and used this Guide from Hackster.io.

It prints a 1 without pressing a button. It does not recognize any key
press. There is no shortcut i change the cable and they are right I
used another keypad same problem :(

How to get other values?


texts:
I am Looking for a Mega 2650 drawing or picture that shows the components labeled.

I've seen the schematics but didn't find a labeled assembly drawing yet.  Should this exist?

Thanks


texts:
I am making a smart bin which automatically sense (with the help of IR sensor ) and dispose the trash by moving with help of DC geared motor 12V 60 RPM and it also detects for obstacles with the help of ultrasonic sensor which is placed at the front of the bin. Once the bin is empty the motor has to spin in the reverse direction. My questions is that there is something wrong in my code and am not able to solve it.

The issue that I am having is that when I run the code the bin was perfectly working as checking whether the bin is empty or not at the start and check for obstacles. If both are clear it will start move and whenever it detects any obstacles, the bin will stop the motor and checks again if any obstacles present, else it will start move and dispose the trash from the bin. The problem is when I code to reverse the motor direction to bring back the bin to original state the relay in relay board making a trrrrr sound.

Project technical specifications:

Arduino Uno
60 RPM 12V DC geared motor
4 channel relay board with 2 relay active for two motors
Ultrasonic sensor
Infrared module
Plunger to open the door placed inside

My sketch:

#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins

LiquidCrystal lcd(10, 11, 5, 4, 3, 2);
int motor_fwd = 7;
int motor_rev = 8;
int plung_rly = 6;
int irsensor = 9;
const int trigPin = 13;
const int echoPin = 12;
int mtr_time = 10;
int mtr_time_rev = 1;

void setup()
{
    digitalWrite(motor_fwd, LOW);
    digitalWrite(motor_rev, LOW);
    digitalWrite(plung_rly, LOW);
    digitalWrite(irsensor, LOW);

    // initialize the relay1 pin as an output;
    pinMode(motor_fwd, OUTPUT); // initialize the relay2 pin as an output;
    pinMode(motor_rev, OUTPUT); // pinMode(irsensor, INPUT);
    pinMode(plung_rly, OUTPUT);
}

void loop()
{
    irsen_chk_low();
    delay(500);
    irsen_chk_high();
    delay(500);
}

void irsen_chk_low()
{
    if (digitalRead(irsensor) == LOW) {
        lcd.begin(16, 2);   // Print a message to the LCD.
        lcd.print("bin Empty");
        delay(500);
        digitalWrite(motor_fwd, LOW);
        if (mtr_time_rev >= 1) {
            mtr_time_rev = mtr_time_rev - 1;
            {
                digitalWrite(motor_rev, HIGH);
                delay(5000);
                digitalWrite(motor_rev, LOW);
                delay(5000);
                int mtr_time = 10;
            }
        }
    }
}

void irsen_chk_high()
{
    if (digitalRead(irsensor) == HIGH) {
        lcd.begin(16, 2);   // Print a message to the LCD;
        lcd.print("Bin is full");
        obs_detection();
        delay(500);
        digitalWrite(motor_fwd, HIGH);
    }
}

void obs_detection()
{
    long duration, inches;
    pinMode(trigPin, OUTPUT);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    pinMode(echoPin, INPUT);
    duration = pulseIn(echoPin, HIGH);
    inches = microsecondsToInches(duration);
    cm = microsecondsToCentimeters(duration);
    lcd.begin(16, 2);
    lcd.print(inches);
    delay(100);
    if (inches <= 10) {
        digitalWrite(motor_fwd, LOW);
        delay(200);
    } else {
        if (mtr_time >= 1) {
            mtr_time = mtr_time - 1;
            digitalWrite(motor_fwd, HIGH);
            delay(200);
        } else {
            int mtr_time = 10;
        }
    }
}

long microsecondsToInches(long microseconds)
{
    return microseconds / 74 / 2;
}


texts: Powering arduino and sensors and motor damaging 16x2 LCD?

texts:
I have an application that requires reading sensors and moving a stepper motor.
The sensors draw about 200mA between them, and need 5V to work. (Too much to draw through the Arduino, I thought) The stepper is recommended to run off 12V, and is driven through a BigEasy board. And, of course, the Arduino needs 5V.

My actual setup has an old laptop power brick, which puts out nominally 12V. This is fed into a voltage regulator (one of the cheap ones with a voltmeter built in) which outputs a steady 5V, even if the input voltage changes a bit. So, I've got a reasonable 12V supply and a fairly fixed 5V supply.

From the 5V supply, I run wiring to the sensors, and from the 12V supply I wire the stepper driver.

The thing is, to power the Arduino, I thought I could just wire up a USB socket (only the power lines) and wire the USB socket to the 5V regulated output. Then I could either plug my arduino into my computer to program it, or plug it into the dummy usb socket to power it standalone.

This arrangement seemed to work for a while, but I've noticed strange behaviour with the 2x16 LCD board which is also attached. I should point out that the LCD takes it's power from the regulated 5V, not from the 5V rail of the Arduino, although the data lines go to the Arduino. The LCD has gone into a "lock-down" mode whereby it only displays half blocks on the top line and nothing else.

I'm wondering if it could be related to effectively powering the system with 2 supplies; one for the majority of the load through the old laptop power brick, and the Arduino through the USB port of my (also laptop) PC. Somewhere along the line, ground get connected to ground, but are all grounds equal?

Is there a standard solution for having the Arduino plugged into your development PC (so as to get debug messages through the Serial COM monitor) whilst still be able to safely power the high-draw loads of the rest of the system. I did consider powering the Arduino through it's barrel jack, but then I'll need an additional 7V supply. (The 5V regulated supply would be too much, and the 12V "semi-regulated" supply would be too much).

And can I do something to protect the next LCD that I use? (Stick a 5.2V Zener across the power pins to prevent spikes??)


texts:
I bought an SG90 servo motor, seller demonstrated by direct supply check, it works there but with Arduino servo sweep check it does not respond: no error during compiling and uploading, but it does not respond.

While other Arduino examples are working correctly like blink example.
I have changed another one but result is the same.

Neither it moves by Arduino nor after installing a grbl shield, where is the problem?


texts:
I'm taking my first wobbly steps outside the Arduino IDE and I'm not having much success with timers / interrupts. I can set a pin to output and light an LED with registers fine but I cannot for the life of me get it to blink using a timer. I have tried numerous tutorials and followed the Atmel ATmega328 datasheet very closely.

Using an Arduino Uno R3 & Atmel ICE (ISP.) My dev system is Raspbian (Debian) with the GNU AVR toolchain (avr-gcc, avr-objcopy, avrdude.) Apart from not having a bootloader it's a bog standard board (including fuses.)

Here's my current code:

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

ISR(TIMER0_COMPA_vect)
{
    PORTB ^= (1 << PB5); // Toggle Arduino Pin #13
}

int main (void)
{
    DDRB = (1 << DDB5); // Arduino Pin #13 is Output

    cli(); // Clear Interrupts

    OCR0A = (unsigned char)0xFF; // Compare Register A = 255
    TIMSK0 = (1 << OCIE0A); // Enable Interrupt for Comp. Reg. A
    TCCR0A = (1 << WGM01); // CTC Mode

    sei(); // Set Interrupts
    TCCR0B = (1 << CS02) | (1 << CS00); // Divide by 1024 Prescaler (GO!)

    return 0;
}

I don't know if I'm just not seeing something or if I've set registers in the wrong order but it's driving me crazy.


texts: How to read a specific amount of data via serial?

texts:
I'm trying to send data via serial from my Arduino nano to my ESP. Its an integer from 1 to 4 digits
so something like 0, 13, 1234, 123, ...

Every thing works fine but when the data comes too fast it stopps the output and  then it print all the data on the screen.

I use this method to recieve data.

void loop() { // run over and over
        if (Serial.available()) {
                incomingByte = Serial.readString();
                Serial.println(incomingByte);
        }
}


texts: Get data as csv file from arduino through an HC05 bluetooth module

texts:
I'm working on a mobile robotic platform and i need data from the sensors and etc.
I have an arduino and a HC-05 bluetooth module. Is there a easy way, like using Putty for example - to get that data straight to my laptop. Thanks in advance.
The mobile platform in question is a differential drive robot with an IMU. I need data from calibration routines through the HC-05 module as the laptop won't be connected while it's moving.


texts: ESP32-POE/ISO unstable after 10 days of power up

texts:
i have one ESP32-POE and ESP32-POE and i'm using the Olimex RS485 module to read a power meter that is placed near the ESP32 (5 meters of CAT5 cable - 9600 8N1).
My device has this workflow (it's powered via PoE using a Cisco 2960x switch):

Boot and acquire a DHCP address
Connect to the server and check if there is a new ota package to download
Read via modbus (Using ModbusMaster library) the power meter
Prepare the data in JSON format using ArduinoJson library and send it to the broker using PubSubClient
Wait for five minutes using Millis and start over with the loop

This is the main logic that "blocks" the loop and wait for some minutes:
void loop() {
  wdt_reset();
  MQTT_connect();

  client_subscriber_loop(); // loop subscriber mqtt

  unsigned long currentMillis = millis();
  if (currentMillis - previousMillisTaskDataPublisher > MQTT_PUBLISH_EVERY) {
    if (DEBUG == 1)
      Serial.printf("Free internal heap on Loop Enter %u\n", ESP.getFreeHeap());
    //  OTA Check
    trueverit_ota_check_update();
    wdt_reset();

    publish_data();
    if (DEBUG == 1)
      Serial.printf("Free internal heap on Loop Enter %u\n", ESP.getFreeHeap());

    previousMillisTaskDataPublisher = currentMillis;
  }
}

As you can see, i've also have Watchdog timer enabled and it is feeded in the loop or function that have to feed it (Modbus read, etc...)
Now, here comes the issues, this works exactly for 10 days and after that the MCU goes in loop, the LAN green led will flash indefinitely and nothing work, leaving the ESP32 in a undefined state.
This is the debug message that i see on arduino console:

There is no way to make it work a part of power off and power on the device.
This is extremely uncomfortable...in my case i have 25 of those devices placed far away from my office (600km) and i can't go every time to reboot them every ten days.
Maybe is hardware related issue? a software issue on ModbusMaster library?
Any toughts?


texts: Have I bricked my Arduino Uno? Problems with uploading to board

texts:
I can't upload sketches to my Arduino Uno.

Have I "bricked" it?
What steps can I take to work out what is wrong?
What can I do to fix it?


texts:
I'm trying out a new ADC, ADS1262, below is the code. I want to discard the first voltage reading.

*/
#include <SPI.h>
#include <SoftwareSerial.h>
#include <math.h>
#include <ads1262.h>

#define PGA 1                     // Programmable Gain = 1
#define VREF 2.50                 // Internal reference of 2.048V
#define VFSR VREF/PGA
#define FSR (((long int)1<<23)-1)

ads1262 PC_ADS1262;                     // class

float volt_V=0;
float volt_mV=0;
volatile int i;
volatile char SPI_RX_Buff[10];
volatile long ads1262_rx_Data[10];
volatile static int SPI_RX_Buff_Count = 0;
volatile char *SPI_RX_Buff_Ptr;
volatile int Responsebyte = false;
volatile signed long sads1262Count = 0;
volatile signed long uads1262Count=0;
double resolution;

void setup()
{
  // initalize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN, INPUT);                  //data ready input line
  pinMode(ADS1262_CS_PIN, OUTPUT);                   //chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);               // start
  pinMode(ADS1262_PWDN_PIN, OUTPUT);                // Power down output

  Serial.begin(9600);
  //initalize ADS1292 slave
  PC_ADS1262.ads1262_Init();                      // initialise ads1262
  Serial.println("ads1262 Initialised successfully....");

 }

void loop()
{
  volatile int i,data;

 if((digitalRead(ADS1262_DRDY_PIN)) == LOW)               // monitor Data   ready(DRDY pin)
  {
    SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();      // read 6 bytes conversion register
    Responsebyte = true ;
  }

  if(Responsebyte == true)
  {
    for(i = 0; i <5; i++)
    {
      SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + i);
    }
    Responsebyte = false;
  }

  if(SPI_RX_Buff_Count >= 5)
  {

    ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];  // read 4 bytes adc count
    ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
    ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
    ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];

     uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)| ((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|      ads1262_rx_Data[3]);//get the raw 32-bit adc count out by shifting
     sads1262Count = (signed long) (uads1262Count);      // get signed value
     resolution = (double)((double)VREF/pow(2,31));       //resolution= Vref/(2^n-1) , Vref=2.5, n=no of bits
// Serial.print(resolution,15);
     volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
     Serial.print(volt_V,8);

   }

  SPI_RX_Buff_Count = 0;

}

float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}


texts: How to use strtok() and strstr() with arduino?

texts:
Can anyone explain how things like strtok() and strstr() can be used to provide a numeric value for a substring location position within the mainstring array.

I've tried to understand from the C++ examples, but their 'position' locations of the substring within the mainstring (which I need) are returned in C++ as %d variables, whereas all I can get returned by the arduino 'char * pointer=' is the actual substring chars if they exist, rather than a number for their start position locations within the mainstring.

The C++ examples show that it is possible to discover the position values from %d,  but how can I get that equivalent position value in arduino?

I want to be able to parse a char header[30] array for occurances of things like "s=123" and "d=789" in order to extract and assign the specified values to any appropriate variables (source or destination etc).


texts:
I want to program an atmega328p-pu via my arduino uno as ISP in a circuit.

I omitted my connected sensors, LCD, etc in the schematic to keep it simple.

When I power the circuit via a 5V power supply (left) I get

avrdude: AVR device initialized and ready to accept instructions

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

avrdude: Device signature = 0x000000 (retrying)

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

avrdude: Device signature = 0x000000 (retrying)

An error occurred while uploading the sketch
Reading | ################################################## | 100% 0.02s

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

avrdude done.  Thank you.

When powering off the circuit and connecting 5V and GND from the arduino to the power and gnd lines in my circuit everything works fine.

I connect 5V and GND from the arduino via pin headers I added to the 5V and GND rails in my circuit to power external sensors etc.

Is there a reason I apparently have to use power from the arduino?


texts: Is it possible to output a variable clock using Fast PWM?

texts:
I am trying output a clock and change its frequency dynamically with a rotary encoder.

When the code for the rotary encoder is included the clock doesn't reach its max freq(31Khz). But without the rotary encoder code, it does. What is happening that it can't reach its max freq?

const byte CLOCKOUT = 9;
int val;
int encoder0PinA = 3;
int encoder0PinB = 4;
int encoder0Pos = 0;
int encoder0PinALast = LOW;
int n = LOW;

void setup() {
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS12);   // CTC, no prescaling
  OCR1A =  0;

  pinMode (encoder0PinA, INPUT);
  pinMode (encoder0PinB, INPUT);
  Serial.begin (9600);
}

void loop() {
  n = digitalRead(encoder0PinA);
  if ((encoder0PinALast == LOW) && (n == HIGH)) {
    if (digitalRead(encoder0PinB) == LOW) {
      OCR1A-=100;
    } else {
      OCR1A+=100;
    }
    Serial.print (OCR1A);
    Serial.print ("/");
  }
  encoder0PinALast = n;
}

The Code that reaches the Max freq properly is below

void setup ()
  {
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS12);   // CTC, no prescaling
  OCR1A =  0;
  }

void loop (){
  }


texts:
I am trying to do something very simple.  I want the LED to fade from full brightness to off.  This works... However, the LED turns back on to full brightness and fades again, in a loop.  I am not sure why.  I think I am missing something obvious.  Once the legThreeBrightness decrements to 0, nothing should happen...
int legThreeBrightness = 255;

void setup() {

    pinMode(3, OUTPUT);

}

void loop() {

    if (legThreeBrightness = 255){
        do {
              analogWrite(3, legThreeBrightness);
              delay(30);
              legThreeBrightness = legThreeBrightness -5;
           } while (legThreeBrightness >= 0);
    }
}


texts: How to use a push button & transistor as a kickstarter for power supply?

texts:
My goal is to save energy, and I intend to do so by powering a chip with itself, and cut power whenever unnecessary. The best image I can have is of a startled monkey who jumps on the branch, screams its profanities while holding to the branch, and when the screams are done, lets go of the branch and falls back on the floor, asleep.
The chip, in my case an ATtiny45, has a program that just makes a specific sound (hopefully more pleasing than an angry monkey's) with a PWM, but would also power an output pin connecting to a transistor acting as a relay between the battery and the power pin.
This is the ideal protocol:
(No closed circuit, no power)
Press Button
Battery power goes through to transistor
Transistor allows current from Battery to PWR pin
Software: Chip starts PWM to Speaker and Outputs constantly the Hold Pin
Hold pin powers the transistor and thus the chip for when the button won't be pressed
Software: When Button still pressed, makes Chip Scream louder
Software: Button not pressed anymore makes chip scream softer until it's done screaming
Software: Scream is finished, stops powering the Hold Pin
Transistor isn't powering the chip anymore.

I think the idea is plausible, though I can't test it at the moment due to not having NPN transistors (?)
My questions are the following:

Truth: Is is possible for a transistor as relay to power a chip on demand?
Risks: Is the power going to be stronger due to the amplifying nature of the transistor? What about the chip, I've read that a chip can maintain its code for 20+ years without power supply. Is this true?
Goals: Is there a better way to save power? Would it be best for the chip to just have sleep enabled?
Name: If this works, is there a better name than the Startled Monkey?

Thanks again for your help, this community has already taught me a lot!

simulate this circuit – Schematic created using CircuitLab


texts: Passing HardwareSerial and SoftwareSerial as a Class Property

texts:
I wish to know if there is a way to use a single property Serial0 to hold a HardwareSerial or a SoftwareSerial or other class instances supporting basic methods such as available(), read() and write(), in order to make a CustomSerial Class (polymorphism?).

class CustomSerial{
    <GenericSerial??> Serial0;
    char c;
    void read(void){
        c=Serial0.read();
    }
};

The calls should be:

CustomSerial SerialCus;
int n=SerialCus.available();
char c=SerialCus.read();
SerialCus.write(c);

What should I use as GenericSerial class, or what should be the proper use? I tried the Stream class (as the answer pointed), but for some reason the functionality is not preserved (it writes unknown characters). Should indeed Stream be the generic class I need for this?


texts: How to produce 6 PWM signals with 60 degrees phase shift?

texts: How to produce 6 PWM signals with 60 degrees phase shift using Arduino Uno 6 PWM pins like in the image below?


texts: Assemble or typecast byte array to float

texts:
The serial port on my Arduino Mega is receiving 3 floats as bytes (total of 12 bytes, 4 per float) over serial. Unfortunately I cannot assemble the 4 Bytes in a float, as the serial monitor only displays

0.00

0.00

0.00 etc.

Here is the code:

void serialEvent2() {
  if (Serial2.available() > 11) {
    byte yawData[3];
    yawData[0] = Serial2.read();
    yawData[1] = Serial2.read();
    yawData[2] = Serial2.read();
    yawData[3] = Serial2.read();
    float yawAngle = *((float*)(yawData));
    Serial.println(yawAngle);

    byte pitchData[3];
    pitchData[0] = Serial2.read();
    pitchData[1] = Serial2.read();
    pitchData[2] = Serial2.read();
    pitchData[3] = Serial2.read();
    float pitchAngle = *((float*)(pitchData));

    byte rollData[3];
    rollData[0] = Serial2.read();
    rollData[1] = Serial2.read();
    rollData[2] = Serial2.read();
    rollData[3] = Serial2.read();
    float rollAngle = *((float*)(rollData));
  }
}

I made sure the data coming to Serial2 is not 0.

UPDATE: The initial mistake was my byte array not being sized correctly. I fixed it. The values I print are fine until after about a second, they get totally weird. Dropped bits/Bytes maybe? Seems odd because a sample sketch written in Processing works perfectly while taking the exact same input.


texts:
I'm new to Arduino (and EE in general), but I am a computer programmer.
I wrote some code and I want to convert it into Arduino code.

Here is the code

# include < stdio.h>
# include < conio.h>
# include < dos.h>

void main()
{
    char *name[8]={{"Danny"},{"Johns"},{"Kim"},{"James"},{"Luci"},{"Merry"},{"Kiara"}};
    for(;;)
    {
        for(int i=0;i<7;i++)
        {
            printf("%s",name[i]);
            delay(1500);
            clrscr();
        }
    }
}

This code prints names infinitely. Now I want to print these names on an Arduino's LCD.

**** **Lcd Pins** ****
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
***************

Please someone provide me code for this and also explain it....


texts: Using Air Quality Sensors like MQ135 to sense dust particles

texts:
Using MQ135 (or similar) to sense dust particles in PM

I was building a Air-purifier system. So, I need to monitor dust particles present in the air. Is it possible to use a gas sensor like the MQ135 to sense dust particles? Since, It can sense very small gas particles. Would it be possible to sense dust particles with it(MQ135 {Cheaper to buy}) or I need to buy a special optical dust sensor {Costly!}


texts: NRF24L01 +pa +lna modules do not communicate

texts:
I am building an rc airplane and I want the controller and the plane to communicate using 2 NRF24L01 +pa +lna modules. I am using an Arduino UNO and a Mega. I hooked them up corresponding to this website (https://howtomechatronics.com/tutorials/arduino/arduino-wireless-communication-nrf24l01-tutorial/).
To program I am using this (https://github.com/nRF24/RF24) library from github. Then I run the GettinStarted sketch from the library on both of the Arduinos one of them with the role set to 0 and one of them with the role set to 1.
Serial monitor for the transmitter:

Now sending
failed
Failed, response timed out.

And for the receiver:

*** PRESS 'T' to begin transmitting to the other node

Is there something I need to change or are the modules broken?


texts: The servo sweep library code - "delay" versus "in steps of"

texts:
This is a pretty basic question - essentially I want to know the difference between adjusting the basic sweep code (from the library) in terms of the "delay" instruction and the "pos += 1" (in steps of 1 degree) instruction.

For my project I want my servo to move 60 degrees at the same frequency as a heart beating relatively fast (lets say two beats a second). I.e., the servo moves from zero to 60 degrees twice in one second. Should I adjust the 'delay' or the 'position' instruction from the library? What's the difference? Does it matter which one I adjust as long as it does what I need it to?

Thanks for your time!


texts: GPS is working but Distance is always showing 0. Can't calculate Distance in this code

texts:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
static const int RXPin = 4, TXPin = 5;
static const uint32_t GPSBaud = 9600;

TinyGPSPlus gps;
SoftwareSerial ss(RXPin, TXPin);
float temp1, temp2;

const char* ssid = "LYN TECH";
const char* password = "pass word";
const char* host = "your host name";
const int trigPin = 2; //D4
const int echoPin = 0; //D3
long duration;
int distance;
int t = 27;

void setup()
{
    Serial.begin(115200);
    Serial.println();
    ss.begin(GPSBaud);

    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    Serial.begin(115200);
    delay(100);
    //Serial.print("Connected to..");
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
}

void checkGPS()
{
    if (gps.charsProcessed() < 10) {
        Serial.println(F("No GPS detected: check wiring."));
    }
}

void loop()
{

    while (ss.available() > 0) {
        // sketch displays information every time a new sentence is correctly encoded.
        if (gps.encode(ss.read()))
            if (gps.location.isValid()) {

                float latitude = (gps.location.lat()); //Storing the Lat. and Lon.
                temp1 = latitude;
                delay(2000);
                float longitude = (gps.location.lng());
                temp2 = longitude;
                delay(2000);

                Serial.print("LAT:  ");
                Serial.println(latitude, 6); // float to x decimal places

                Serial.print("LONG: ");
                Serial.println(longitude, 6);
            }
    }

    WiFiClient client;
    const int httpPort = 80;
    if (!client.connect(host, httpPort)) {
        Serial.println("Connection failed");
        delay(1000);
        return;
    }

    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    distance = duration * 0.034 / 2;
    Serial.print("Distance: ");
    Serial.println(distance);
    Serial.println(WiFi.localIP());
    String url = "your url.php?dist=" + String(distance) + "&lat=" + String(temp1, 6) + "&lng=" + String(temp2, 6);
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                "Host: " + host + "\r\n" +
                "Connection:close\r\n\r\n");
}


texts: The Arduino Sketch does not save in Arduino folder location

texts:
I have just installed Arduino on Mac OS. The Arduino folder is created under Documents. But whenever I save the sketch it gets stored in some ghost location and gives an error, the same name already exits. Upon finding the location of file. It gets stored under this directory(Hidden).

/private/var/folders/_v/nbrwcsh51wd2k07kfhy9vhjm0000gn/T/untitled1010592992.tmp/sketch_sep28a

How can I move this location to my documents folder. In Arduino preferences, I have also changed the location of sketch, still it does save in above location.


texts: Writing a 32-bit register to 32 pins as fast as possible in Arduino Due

texts:
Problem:

I'm using Due's QDEC function to decode a 32bit quadrature encoder.
I need to pipe out the counter value as fast as possible to another instrument's DIO.
The rear strip is selected as digital output because it's easy to slap an IDC connector on it.

#define QA 2
#define QB 13
const unsigned int mask_QA = digitalPinToBitMask(QA);
const unsigned int mask_QB = digitalPinToBitMask(QB);

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

    // QDEC block
    REG_PIOB_PDR = mask_QA;     // activate peripheral function
    REG_PIOB_ABSR |= mask_QA;   // choose peripheral option B
    REG_PIOB_PDR = mask_QB;
    REG_PIOB_ABSR |= mask_QB;

    REG_PMC_PCER0 = (1<<27);                                // activate clock for TC0 (PID27)
    REG_TC0_CMR0 = (1 << 0) | (1 << 2) | (1<<8) | (1<<10);  // config clock
    REG_TC0_BMR = (1<<9)|(1<<8)|(1<<12);                    // activate QDEC
    REG_TC0_CCR0 = 5;                                       // enable the clock and reset counter

    //PIO BLOCK
    // mask write, the rear strip of Arduino Due
    REG_PIOA_OWER = 0x0018c808; // A 7 14 15 19 20
    REG_PIOB_OWER = 0x04204000; // B 14 21 26
    REG_PIOC_OWER = 0x000FF3FE; // C 1-9 12-19
    REG_PIOD_OWER = 0x0000064F; // D 0 1 2 3 6 9 10
}
void loop() {

  // data write
  REG_PIOA_ODSR = REG_TC0_CV0;
  REG_PIOB_ODSR = REG_TC0_CV0;
  REG_PIOC_ODSR = REG_TC0_CV0;
  REG_PIOD_ODSR = REG_TC0_CV0;
}

This code is untested as I don't have access to the hardware right now.
Basically 4 bit masks (for PIO ABCD) are created to map the 32bit REG_TC0_CV0 onto the rear strip.

Requirement:

[Priority] As little delay as possible, every clock cycle matters.
[Secondary] Output bandwidth should match the update rate of REG_TC0_CV0, which I didn't manage to find in the manual. The output should also provide a latch for the receiving equipment to sync sampling.

Question:

Would disabling peripheral functions for all 32 pins on the rear strip interfere with the core functionality that this program depends on (timer/counter etc) ?
Are there other ways that can accomplish this faster ?
I would like to use the main CPU tread for serial interface. It is possible to attach the four ODSR writing instructions to a timer ISR so it does not interfere with void loop()?

Thanks in advance !


texts: Encoder code using interrupts design question

texts:
I have an Arduino Mega 2560, an Omron Optical encoder with an Index (360 steps), a 60 led NeoPixel ring (no Clk wire) and another Arduino Uno.
Here is my question, I have some code written that works with the Arduino Mega and optical encoder outputting decently to the serial monitor for diagnostic purposes.
When I add the additional code to run the Neopixel ring I get a terrible response on the ring.  I have tried the NeoPixel and FastLED libraries with the same terrible success.  It even states in their documentation that they don't work well with interrupts.  I started thinking about sending the 3 digit output to a Direct Pin output from the Mega to be read by another Mega/Uno to run the Neopixel Ring and a 4x20 LCD screen. Does anyone else have any ideas on this.  Below is my code for the Mega and the Encoder.

    // Wiring connections for my encoder:
    // Brown : VCC = 5V
    // Blue + Shield : 0V = GND
    // Black : ENCODER0PINA, Pin 18
    // White : ENCODER0PINB, Pin 17
    // Orange : ENCODER0PINI, Pin 19

    #define ENCODER0PINA         18      // this pin needs to support interrupts
    #define ENCODER0PINB         17      // no interrupt required
    #define ENCODER0PINI         19      // this pin needs to support interrupts

    // variables modified by interrupt handler must be declared as volatile
    volatile long encoder0Position = 0;
    volatile long interruptsReceived = 0;
    volatile byte INTFLAG1 = 0;

    // track last position so we know whether it's worth printing new output
    long previousPosition = 0;

    void setup()
    {
      // inputs
      pinMode(ENCODER0PINA, INPUT);
      digitalWrite(ENCODER0PINA, HIGH);  // turn on pullup resistor
      pinMode(ENCODER0PINB, INPUT);
      digitalWrite(ENCODER0PINB, HIGH);  // turn on pullup resistor
      pinMode(ENCODER0PINI, INPUT);
      digitalWrite(ENCODER0PINI, HIGH);  // turn on pullup resistor

      // interrupts
      attachInterrupt(5, onInterrupt, RISING);  // encoder track A on interrupt 3 - pin 18
      attachInterrupt(4, onReset, RISING);  // encoder Index track on interrupt 4 - pin 19

      // enable diagnostic output
      Serial.begin (115200);
      Serial.println("Ready.");
    }

    void loop()
    {
      // only display position info if has changed
      if (encoder0Position != previousPosition )
      {
        Serial.println(encoder0Position, DEC);

        previousPosition = encoder0Position;
      }
    }

// interrupt function needs to do as little as possible

void onInterrupt()
{
  // read both directional inputs
  int a = digitalRead(ENCODER0PINA);
  int b = digitalRead(ENCODER0PINB);

  if (a == b)
  {
    // b is leading a (counter-clockwise)
    encoder0Position--;
    if (encoder0Position < 0)
    {
      encoder0Position = ((encoder0Position + 360) % 360);
    }
  }
  else
  {
    // a is leading b (clockwise)
    encoder0Position++;
    if (encoder0Position >= 360)
    {
      encoder0Position = ((encoder0Position - 360) % 360);
    }
  }
}

void onReset()
{
  // read Index input
  int i = digitalRead(ENCODER0PINI);
  if (i == 1)
    {
  encoder0Position = INTFLAG1;
    }
}


texts: Use a Unicode surrogate pair character in Arduino IDE

texts:
I'm writing a sketch for a Wemos D1 Mini to display a web page. This works and I can get Unicode characters to display, but if I try to use ones with surrogate pairs like 🔊 I get a compile error;

  s += "\uD83D\uDD0A";

Error

  \uD83D is not a valid universal character

How can I get this character in my code?


texts:
I'm trying to read 4 analog inputs (1kHz speed). I changed the prescaler to 16 for my Arduino Leonardo according to this link. I then tried to read the analog pins and I used the following code to display the time and the readings:

#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
double t = 0;
void setup() {
  int start;
  int i;
  #if FASTADC
  // set prescale to 16
  sbi(ADCSRA, ADPS2);
  cbi(ADCSRA, ADPS1);
  cbi(ADCSRA, ADPS0);
  #endif

  Serial.begin(9600);
  Serial.print("ADCTEST: ");
  start = millis();
  for (i = 0 ; i < 1000 ; i++)
    analogRead(0);
  Serial.print(millis() - start);
  Serial.println(" msec (1000 calls)");
}

// the loop routine runs over and over again forever:
void loop() {
  // print out the value you read:
  t = millis() / 1000;
  Serial.print(t);
  Serial.print('\t');
  Serial.print(analogRead(A0)); delay(1);
  Serial.print('\t');
  Serial.print(analogRead(A1)); delay(1);
  Serial.print('\t');
  Serial.print(analogRead(A2)); delay(1);
  Serial.print('\t');
  Serial.println(analogRead(A3)); delay(1);
}

I connected 2V from the DC supply to all the 4 channels and the readings were similar. I used the output from the serial monitor and pasted the readings for 1 sec in Excel to see the frequency. With a 9600 baud rate and no delay between the readings I got 200 Hz (for the 4 analog inputs).

Why is that happening? And is there a relationship between the sampling frequency and the baud rate? Is my way of finding the frequency correct? If not what's the right way?

Finally, I'll be plotting the readings in Matlab, so I guess this will affect the sampling frequency. How can I control it so that I'm sampling with 1kHz rate for all the channels?

Here is the screenshot of the readings from the 4 channels (2V input).

Summarizing everything, I need to know the following:

The effect of adding a delay between every two readings on the accuracy of the readings and the sampling frequency.
How to find the best sampling frequency for every input and how to control it?
Will using Matlab to plot the data affect the sampling frequency?

Thanks.

EDIT: I accepted the answer below, if anyone has the same problem , please make sure that you change the prescaler as I mentioned above for the best results.


texts:
(Before you down-vote this, note that it is a "ringer" to answer a FAQ, with a self-answer.)

This question comes up all the time. How do you combine 2 different sketches together? Say I have a sample sketch for a DTH temp/humidity sensor and another sketch for a LCD sensor. How do I combine them?


texts:
Will a delay() function in a void SerialEvent() also stop the code that is running in the void loop() function?

This is about an Arduino Uno.


texts: Which Timer can I use to control a servo with Arduino Uno

texts:
I would like to control 2 motors using Timer2 @ 200Hz. The frequency of the timer is printed in the main loop every second. I'm using an Arduino Uno with two interrupt used for the encoders connected to pin 2 and 3.

The problem

The timer runs at 200Hz as expected but the motors are shaking even if I ask them not to spin. The Timer2 is not required by the servo library.

How can I solve this problem? How do you handle Timer interrupts and servo routines?

CODE

#include <Servo.h>
Servo motorDx, motorSx;
[...]

void setup()
{
  // Setup Timer2 @ 200Hz
  cli(); // Stops interrupts

  TCCR2A = 0;// set entire TCCR1A register to 0
  TCCR2B = 0;// same for TCCR1B

  // set compare match register for 200 Hz increments
  OCR2A = 77;// = (16*10^6) / (200*1024) - 1 -> 200 Hz

  // turn on CTC mode
  TCCR2A |= (1 << WGM21);
  // Set CS10 and CS12 bits for 1024 prescaler
  TCCR2B |= (1 << CS20) | (1 << CS21) | (1 << CS22);
  // enable timer compare interrupt
  TIMSK2 |= (1 << OCIE2A);

  sei(); //enable global interrupts

  attachInterrupt(0, MSencVel, RISING);
  attachInterrupt(1, MDencoder, RISING);
  motorDx.attach(10, 1000, 2000);
  motorSx.attach(11, 1000, 2000);
}

void loop()
{
  if(micros()-tOld >= 50000)
  {
    tOld = micros();
    count += 1;
    if(count >= 20) // Runs @ 1 Hz
    {
      count = 0;
      serialRoutine();
      // prints number of ISR/sec
      Serial.println(contIsr)
      contIsr=0;
    }
  }
}

ISR(TIMER2_COMPA_vect)
{
  //sendValuesToMotors();
  motorDX.write(90);
  contIsr++;
}


texts: HC-SR04 systematically finding a weird value

texts:
I have a HC-SR04 connected to my Arduino. its all working very nice. Yet with a constant interval a weird value appears (see the Serial Plot picture). I am wondering what causes this. I will soon upload my Sketch (Making it bit more readable).

Or are there to many possible factors that could influence the HC-SR04 behaviour that it is impossible to determine the cause?

Y-axis shows distance in cm, x-axis shows iteration (once a second)

Thanks in advance!

Kind Regards, a fellower Arduino User


texts:
I have developed my arduino code using below library. I tested code working fine over modbus RTU slave. Now i am planning to use RS485 to wifi instead of wire connection. In order to get data over web apllication i need to add another layer of modbus TCP-IP. can some one suggest me is it possible to without changing any hardware add library function which can acts like MODBUS RtU over TCP-IP protocol.

if any library avilable please share it
I am using WIFI device like below.
rs485 to wifi

MODBUS RTU


texts: Can Serial be safely used in an SPI interrupt routine

texts: I have anecdotal experience that using Serial.print inside a slave's SPI interrupt routine (ISR) causes issues with transmission. It also seems that interrupts may be called more than once before the main loop can react, so it is difficult to print info from all interrupts. Is this because Serial is inherently unsafe, or too slow? Can Serial be used safely inside the ISR routine?


texts:
If I do following:

pinMode(MYPIN, OUTPUT)
digitalWrite(MYPIN, LOW)

What will happen? Will this effectively ground MYPIN or output some low voltage?


texts:
I'm installing some daylight running lights in my car and I have purchased 2 LED bars, each with 8 white LEDs. They use 12V and I need to make some effect when they turn on. Like in some modern cars, when I turn on the key, LEDs should blink(shake like when old fluorescent tubes turns on) and then turn on slowly(brightness from 0-100).

I can do this with Arduino-Uno and I need to put this in a smaller chip. What would be the best suitable ATTiny chip for this project? Because using an ATmega328 is not worth for a small project like this.


texts: Can I use an Arduino Uno-style Shield with the Arduino Mega, Tre, or Zero? How about the Intel Edison?


texts:
Are there any caps available for these buttons, or am I better off using other, more stylish buttons if I want to make a presentable arduino-based gadget?

The circular hole drilled in their square-section moving part seems to suggest that something can be plugged there, but I can't seem to find caps anywhere.

Thanks for your attention.


texts: Arduino command line vs. Arduino builder

texts: I'm working on adding my Arduino to continuous integration and I came across two different possible ways of doing this, Arduino command line, and arduino-builder.  Can someone explain why the arduino-builder tool exists separately from calling Arduino from the command line?  And what are the advantages of using one over the other?


texts:
I have a Seeed Studio SD card shield (V3) that I am trying to use on my Arduino Due. I am having trouble using the SD examples that come with the Arduino IDE.

They worked fine on my Arduino Uno by setting chipSelect to SS. Below is the code I used for the Arduino Uno. It is the same as the CardInfo.ino in the examples section under SD (except for the chipSelect).

CardInfo.ino

    /*
      SD card test

 This example shows how use the utility libraries on which the'
 SD library is based in order to get info about your SD card.
 Very useful for testing a card when you're not sure whether its working or not.

 The circuit:
  * SD card attached to SPI bus as follows:
 ** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila
 ** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila
 ** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila
 ** CS - depends on your SD card shield or module.
        Pin 4 used here for consistency with other Arduino examples

 created  28 Mar 2011
 by Limor Fried
 modified 9 Apr 2012
 by Tom Igoe
*/

// include the SD library:
#include <SPI.h>
#include <SD.h>

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
const int chipSelect = SS; //CHANGE HERE!!!!!!!!

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.print("\nInitializing SD card...");
  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  // Note that even if it's not used as the CS pin, the hardware SS pin
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output
  // or the SD library functions will not work.
  pinMode(10, OUTPUT);     // change this to 53 on a mega

  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card is inserted?");
    Serial.println("* Is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    return;
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }

  // print the type of card
  Serial.print("\nCard type: ");
  switch (card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    return;
  }

  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("\nVolume type is FAT");
  Serial.println(volume.fatType(), DEC);
  Serial.println();

  volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume.clusterCount();       // we'll have a lot of clusters
  volumesize *= 512;                            // SD card blocks are always 512 bytes
  Serial.print("Volume size (bytes): ");
  Serial.println(volumesize);
  Serial.print("Volume size (Kbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Mbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);

  Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  root.openRoot(volume);

  // list all files in the card with date and size
  root.ls(LS_R | LS_DATE | LS_SIZE);
}

void loop(void) {

}

Here is a picture of my setup:

tl;dr

How do I make this shield work on my Due?


texts: Deviation of power consumption between datasheet and real world?

texts:
According to the Atmega328P-PU Datasheet (side: 589) the current consumption of the microcontroller should be around 9.5mA (at 16MHz and 5V).
But I measured 15mA. (Nick Gammon who did some pretty good power saving research(gammon.com.au/power) got the same)
There is nothing connected to the outputs. The code I ran was this:

  void setup () {}
   void loop () {}

Now I'm wondering if this is just a normal deviation (datasheet to real world) or if Atmel measured their current consumption in a state that is different from mine?

EDIT:

I forgot to mention.. I didn't use it with the Arduino Uno board but as standalone device. There was only a 16Mhz oscillator with two capacitors connected. Power came directly form Power supply.

Now that I think about it..  Datasheet says this regarding the current measurement: "A sine wave generator with rail-to-rail output is used as clock source."

Is it possible that the oscillator needs that extra 5mA?

EDIT2:

Here is a screenshot of my schematic:

And a screenshot of the ATmega328P-PU Datasheet:


texts: Waveshare Display on ESP32 has weird graphic glitches

texts:
I am trying to pass an image to the display through the GxEPD module. I tested the display and its working fine with an example sketch.

I am using a WEMOS LOLIN32 and a 7,5" B/W Waveshare display.

When I add any other image after converting it to hex values, this happens:

This is the image in GIMP:

And this is what the display shows:

As you can see, the display shows the image glitched a lot. It looks a lot like each "row" of a few pixels is mirrored horizontal. The question here is: Why? All I did was converting the image in GIMP to .xbm, taking the content, stripping whitespace, pasting the Arduino syntax around the code and replacing the example file with this one.


texts:
Recently we purchased servos for use in an Arduino and began testing with servos. It turned out that the uSec for the servos differed from the online documentation and we had to find the min and maxes of the uSecs manually:

while (Serial.available()) {
    char c = Serial.read();  //gets one byte from serial buffer
    readString += c; //makes the string readString
    delay(2);  //slow looping to allow buffer to fill with next character
}

if (readString.length() >0) {
    Serial.println(readString);  //so you can see the captured string
    int n = readString.toInt();  //convert readString into a number
    Serial.print("writing Microseconds: ");
    Serial.println(n);
    myServo.writeMicroseconds(n);
    readString = ""; //empty for next input
}

The issue is that the servos don't travel the full 180 degree advertised price (more like 135-160) and that lack of angular distance is affecting performance of one of our products. The servos can even mechanically travel a noticeable distance farther than 180, but not "programmatically" farther even when given a larger PWM uSec value that the observed "max" PWM value

What I've found

I looked around and apparently there are "Servo Programmers" to calibrate endpoints and midpoints, but cost an arm and a leg. I find it strange that I would have to "program" my servos. I was part of an First (FTC) robotics team using tetrix/nxt electronic control systems, and never noticed a problem with uSec values or not getting the full range of motion using the same brand of servos I currently am now.

  How can I perform a low cost, easy way to simply get the full range
  of motion I paid for?


texts:
Is is possible to read from serial window till timeout?

Actually, what I am looking for is a function that reads from serial monitor, and if no data is available in serial monitor, then it should wait for some time and if still no data is arrived it should return.

Something like,

Serial.read(int timeout);


texts:
When I try to compile my code it says "stray '\342' in program

My code:

#include <IRremote2.h>
#include <IRremoteInt.h>

#define pinIN 11

uint32_t val;
uint32_t prev;
int fre = 0;

IRrecv remote(pinIN);
decode_results result;

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

  remote.enableIRIn();
  pinMode(2, OUTPUT);
}

void loop() {
  if (remote.decode(&result)) {
    val = result.value;
    if (val == 0xFFFFFFFF) {
      val = prev;
    }
    prev = val;
    detekceKlaves();

    remote.resume();
  }
}

void detekceKlaves() {

  switch (val, HEX) {

    case 0x807FB24D:
      Serial.println("Stisknuto PLAY");
      tone(2, fre);
      break;
    case 0x807FB04F:
      Serial.println("Stisknuto STOP");
      noTone(2);
      break;
    case 0x807F18E7:
      Serial.println("Stisknuto VOL+");
      fre += 10;
      break;
    case 0x807F906F:
      Serial.println("Stisknuto VOL-");
      fre -= 10;
      break;
    case 0x807F9867:
      Serial.println("Stisknuto OFF/ON");
      fre = 0;
      break;
    default:
      Serial.println("Stisknuta jina klavesa");

  }
}

Error code:

Arduino: 1.8.10 (Windows 10), Board: "Arduino Uno"

irTEST:43:20: error: stray '\342' in program

     case 0x807FB24D:

                    ^

irTEST:43:21: error: stray '\200' in program

     case 0x807FB24D:

                     ^

irTEST:43:22: error: stray '\254' in program

     case 0x807FB24D:

                      ^

irTEST:47:10: error: stray '\342' in program

     case 0x807FB04F:

          ^

irTEST:47:11: error: stray '\200' in program

     case 0x807FB04F:

           ^

irTEST:47:12: error: stray '\255' in program

     case 0x807FB04F:

            ^

irTEST:47:23: error: stray '\342' in program

     case 0x807FB04F:

                       ^

irTEST:47:24: error: stray '\200' in program

     case 0x807FB04F:

                        ^

irTEST:47:25: error: stray '\254' in program

     case 0x807FB04F:

                         ^

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino: In function 'void detekceKlaves()':

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:43:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807FB24D:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:47:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807FB04F:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:51:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807F18E7:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:55:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807F906F:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:59:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807F9867:

     ^~~~

Multiple libraries were found for "IRremote2.h"
 Used: C:\Users\maxim\Documents\Arduino\libraries\IRremote2
exit status 1
stray '\342' in program

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

Please help