texts: Is there a constant for the Maximum Unsigned Long value in an Arduino compiler?

texts:
I am writing a timer function that uses the micros() function which generates a unsigned long value.  To compensate for a roll over condition, I would like to use the maximum value for that variable type.  I have a number, 4,294,967,295, but was expecting that to be a constant somewhere.

Is there a MAX_UNSIGNED_LONG constant in the Arduino compiler files somewhere?

I have tried that name and know it probably isn't that.  Still poking around.


texts:
So I built my First LED Cube and the thing turns ON!!! Pretty happy about that but here is my problem.

When I try and get the Cube to display say a basic "outline" (a wire form of a cube only the outer most LEDs are on)

The shift registers, that I have daisy chained together, give the correct display 80% of the time, but the other 20% give completely wrong LEDs lighting up.

I have used 4 74HC595 shift registers linked together so I am only using 3 of my Arduino ports to control the 5*5*5 Cube.
The basic shape is there but the ones that are not meant to be lighting up cause a lot of flickering (or ghosting?) in the center of the cube.

I have thought about using pull up or pull down resistors but I find that, when I run my program at a slower rate, the LEDs that are lighting wrongly are lighting up controlled so I think it has to be something with my code or setup.

Has anyone got any experience with LED cubes doing this?

Also I am only using the output enable and disable to make use the wrong this is not displayed when I am shifting the data out, should I be using the clear?

One last thing, does anyone have recommendations for the delay time to let each layer shine for?

My code is below

int clockPin = 8;
int dataPin = 7;
int set = 6;

void setup()
{
  //set pins to output so you can control the shift register
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(set,OUTPUT);
}

void loop()
{
      digitalWrite(set,HIGH); // DISABLES OUTPUT
  // level 1 ( top )
      shiftOut(dataPin, clockPin, MSBFIRST, B00000011);//from left 3rd to the 7th = levels 5-1,, The right first LED
      shiftOut(dataPin, clockPin, MSBFIRST, B11111000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B11000110);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00111111);// Makes the " wire cube "
      digitalWrite(set,LOW);  // enables output
      delay(2);

       digitalWrite(set,HIGH); // DISABLES OUTPUT
 // level 2
      shiftOut(dataPin, clockPin, MSBFIRST, B00000101);//from left 3rd to the 7th = levels 5-1,, The right first LED
      shiftOut(dataPin, clockPin, MSBFIRST, B00010000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00000000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00010001);// Makes the " wire cube "
      digitalWrite(set,LOW);  // enables output
      delay(2);

      digitalWrite(set,HIGH); // DISABLES OUTPUT
 // level 3
      shiftOut(dataPin, clockPin, MSBFIRST, B00001001);//from left 3rd to the 7th = levels 5-1,, The right first LED
      shiftOut(dataPin, clockPin, MSBFIRST, B00010000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00000000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00010001);// Makes the " wire cube "
      digitalWrite(set,LOW);   // enables output
      delay(2);

      digitalWrite(set,HIGH); // DISABLES OUTPUT
 // level 4
      shiftOut(dataPin, clockPin, MSBFIRST, B00010001);//from left 3rd to the 7th = levels 5-1,, The right first LED
      shiftOut(dataPin, clockPin, MSBFIRST, B00010000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00000000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00010001);// Makes the " wire cube "
      digitalWrite(set,LOW);   // enables output
      delay(2);

      digitalWrite(set,HIGH); // DISABLES OUTPUT
 // level 5 ( bottom )
      shiftOut(dataPin, clockPin, MSBFIRST, B00100001);//from left 3rd to the 7th = levels 5-1,, The right first LED
      shiftOut(dataPin, clockPin, MSBFIRST, B11111000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B11000110);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00111111);// Makes the " wire cube "
      digitalWrite(set,LOW);   // enables output
      delay(2);
}

Any help would be appreciated

Thanks


texts:
i can't figure this out, i have a task to get data from RX module that led has turned on.
The Idea. I press push button on TX part, and led diode turn on, on RX part. Then RX send's data to TX that led have been turn'd on and print "LED HAVE BEEN TURNED ON".
I have made turn on part, but i struggle with sending from rx to tx. When i add this part code just stops
 while (!radio.available()); {
   radio.read(&buttonState, sizeof(buttonState));
   if (buttonState == 0) {
     Serial.print("LED HAS BEEN TURNED ON");
     Serial.print("\n");

//RX
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define led1 6
#define mot 5

int buttonState = 0;

bool ledbutton = 0;

RF24 radio(9, 8);
const byte address[][6] = {"00001", "00002"};

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

  pinMode(led1, OUTPUT);
  digitalWrite(led1, HIGH);

  pinMode(mot, OUTPUT);
  analogWrite(mot, HIGH);

  radio.begin();
  radio.setChannel(80);
  radio.setDataRate(RF24_250KBPS);
  radio.setPALevel(RF24_PA_HIGH);

  radio.openWritingPipe(address[0]); // 00001
  radio.openReadingPipe(1, address[1]); // 00002

  radio.setPALevel(RF24_PA_MIN);

}
void loop() {
  radio.startListening();
  if ( radio.available()) {
    while (!radio.available()); {
      radio.read(&buttonState, sizeof(buttonState));

      ledON();
      motON();
    }
    radio.stopListening();
    ledbutton = digitalRead(led1);
    radio.write(&ledbutton, sizeof(ledbutton));
  }
}

void ledON() {
  if (buttonState == 1) {
    digitalWrite(led1, LOW);
  }
  else  if (buttonState == 0) {
    digitalWrite(led1, HIGH);
    Serial.print("LED ON");
    Serial.print("\n");
  }

}

void motON() {
  if (buttonState == 3) {
    analogWrite(mot, 0);
  }
  else  if (buttonState == 2) {
    analogWrite(mot, 255);
    Serial.print("MOTOR ON");
    Serial.print("\n");
  }

}

//TX
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define buttonPin1 7
#define buttonPin2 4

int buttonState1 = 0;
int buttonState2 = 0;

int ledbutton = 0;

RF24 radio(9, 8);
const byte address[][6] = {"00001", "00002"};

void setup() {
  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);

  Serial.begin(9600);

  radio.begin();
  radio.setChannel(80);
  radio.setDataRate(RF24_250KBPS);
  radio.setPALevel(RF24_PA_HIGH);

  radio.openWritingPipe(address[1]); // 00002
  radio.openReadingPipe(1, address[0]); // 00001

}
void loop() {
  radio.stopListening();
  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);

  LedControl();
  MotorControl();

  radio.write(&buttonState1, sizeof(buttonState1));
  radio.write(&buttonState2, sizeof(buttonState2));

  delay(5);
  radio.startListening();
  while (!radio.available()); {
    radio.read(&ledbutton, sizeof(ledbutton));
    if (ledbutton = 0) {
      Serial.print("LED HAS BEEN TURNED ON");
      Serial.print("\n");
    }
  }
}

void LedControl() {
  if (buttonState1 == 1) {
    buttonState1 = 1;
  }
  else  if (buttonState1 == 0) {
    buttonState1 = 0;
  }
  Serial.print(buttonState1);
  Serial.print("\n");
}
void MotorControl() {
  if (buttonState2 == 1) {
    buttonState2 = 3;
  }
  else  if (buttonState2 == 0) {
    buttonState2 = 2;
  }
  Serial.print(buttonState2);
  Serial.print("\n");
}


texts:
I have a problem with my Arduino Uno board. It's not mounting in my Linux machine, but its power is on and the LED light is glowing. It was working before. After I tested buttons with an 12 V external supply, I am facing this scenario.

I tried lsusb and I checked /dev/ ports. Also, I couldn't find `ttyACM. I tried with another Arduino board and it's working. I think the board is gone, and I need help to fix this problem.

I thought it was a bootloader problem, and I got a new ATmega328P chip board. It is getting power on and the LED is blinking, but the port is not mounted. I tried with lsusb and also ls /dev/ttyACM* with no result.


texts: How to forward sms using arduino uno + gsm shield

texts:
hey there I'm new to arduino. I'm working on a project that needs to send an sms to get a response and forward the response to another mobile.
What is the easiest way to do so


texts:
So I am trying to make a Mac OSX program with Cocoa that will be able to control my Arduino via serial. I currently have the C command

popen("echo 7 > /dev/cu.usbmodem1411", "r");

to try to send the number 7 over serial to the Arduino. I know that the path     /dev/cu.usbmodem1411 is correct because the Arduino is responding, however it seems to "crash" or simply restart whenever this command is received from the Mac. Sorry this may be a question for StackOverflow, but I thought I would start here.


texts: Need Input: Wait for voltage input to begin script & when voltage maintains 0V for X amount of time Reset and wait for Voltage Input

texts:
So I'm currently working on an automotive set up.

I'm using a 555 timer to emulate a turn-signal alternating voltage pulse (12V to 0V and repeat) for debugging purposes which is output to turnPin/A1.

Here's the goal: When voltage is greater than 1V arduino is to supply constant power to output pin (pin 13) until input voltage is returned to constant 0 (or end of turn signal input) for x-time or as I'll refer to as Timeout.

It seems I've gotten the constant power to apply when input is applied and then turn off constant output when voltage is back to 0V. However I'm having difficulty getting the timeout function to work properly as the LED still remains HIGH.

EDIT: I've reworked the code to use millis(); rather than purely using sensor inputs. I've also added comments to help walk you through what I believe is happened/what I want to happen.

// Constants won't change
const int ledPin = LED_BUILTIN; //using built in led + pin13
const int turnPin = A1;         // the input pin (turn signal alternating 5V/0V/5V/0V & so-forth)

// Variables will change
int ledState = LOW;             // the current state of the output pin
int prevLed = ledState;
int lastVoltage = 1;            // the previous reading from voltage source
int state = 1;                      // the current "state" (see below)
                                // State = 1++: LED OFF -- State = 0: LED ON

// The following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.

long previousMillis = 0;    //the last time the voltage reached 0
long waitTime = 100;    // the wait time

void setup()
{
  pinMode(ledState, OUTPUT);        //set output pin
  pinMode(turnPin, INPUT);          //set input pin NOTE: SIGNAL ALTERNATES
5V/0V/5V/0V & so forth to emulate a turn signal for this application
  Serial.begin(9600);               //begin serial
}

void loop()
{
  int sensorValue = analogRead(turnPin);        // Read voltage at input pin
  float voltage = sensorValue * (5.0/1023.0);   // Convert
  unsigned long currentMillis = millis();    // set currentMillis as current
 time

  if (voltage > 1)      //if Voltage greater than 1V
  {
    ledState = HIGH;    //turn led on
    state = 0;          //set state to 0
  }

  if (voltage < 1)      //if voltage less than 1V
  {
    currentMillis;      //set currentMillis as current time

    if ((millis() - currentMillis) > waitTime) // if (current time minus time voltage was less than 1) is greater than wait time
    {
        ledState = LOW;     //set LED to off
        Serial.print("OFF - TIMED OUT - WAITING FOR INPUT: ");  //output message for debug
        Serial.println(state);//current state
        state++;              //increment state (time passed)
    }
        else if ((millis() - currentMillis) < waitTime) // if (current time minus time voltage was less than 1) is less than wait time
        {
            ledState = HIGH;    //set LED to on
        }
  }
  digitalWrite(ledPin, ledState);   //send LED status to output
}


texts:
Scenario: I would like to monitor my closet's door as I highly suspect a family member is opening and using my items without permission. To respect privacy and also because my closet is nowhere near a power mains, I don't need video nor audio recording. I also do not need indicator lights etc because I intend to turn it on when I go to work and check the logs on the SD card when I return home. A typical day would require the device to run for 12 hours minimally.

Aim: Is it possible for Arduino to achieve the following,

Run on batteries for at least 1 month
Detect motion
Logging the detection motion onto a text file in a SD card

Or do I have to look elsewhere for this functionality?

Current understanding: I am aware Arduino can run on batteries though I've never been able to get it to last more than 3 hours. Probably has to do with me not using the low power mode or something and that my batteries were being stepped up. I also know that Arduino has some PIR motion sensors though I don't quite remember how power hungry these sensors are. I have NEVER tried logging onto an SD card using Arduino. This sums up my experience with Arduino.

Any advice would be much appreciated. Thank you.


texts: ISP Programmer with Serial and 5v/3.3v power

texts:
I currently use a Pololu USB AVR Programmer v2.1 for programming 328p chips and I really like it. The ability to have ISP and Serial in one physical device, enumerating as two separate COM ports on the PC, the programmer powering the circuit at 3.3v, with the programmers windows GUI interface to set voltages, programming frequency and give feedback on the programming when things go wrong, is all brilliant.
However, many of my circuits either have a power requirement higher than that on the Pololu (80mA), or to much capacitance (33uF) so that the power surge on connection is too much for the Pololu and it resets.  The reset disconnects my serial debugger, disconnects the Pololu GUI, and sometimes does not come back on at all due to the startup current draw.
I am looking for suggestions for an alternative device, or way of stopping the brown out on power up?
Thanks very much
Kevin


texts: Arduino Uno and Arduino Yun software. Which version of the IDE works with both best?

texts:
I have been working with Unos and just started working with Yun. I have 1.86 currently installed but the Yun starts up saying to use 1.5.6-r2 Beta IDE. Should I uninstall 1.8.6 and install 1.5.6-r2?

Thanks for your help.

Lisa


texts: Can't burn bootloader, Says Invalid device signature

texts:
I am trying to burn bootloader on an Atmega 328P-PUon breadboard with minimal circuit using Arduino UNO, following up this Arduino Tutorial : https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard (See Minimal configuration).

Arduino board also has Atmega328 on it.

I followed up tutorial exactly as it says, triple checked connections. But upon clicking Burn Bootloader after selecting "ATmega328 on a breadboard (8 MHz internal clock)" from boards and select "Arduino as ISP" in programmers it throws error :

Expected signature for ATmega328P is 1E 95 0F
Double check chip, or use -F to override this check.

Now, Obviously it means it doesn't thinks I have 328 on breadboard. BUT I HAVE!

The thing is the hardware file https://www.arduino.cc/en/uploads/Tutorial/breadboard-1-6-x.zip it says is for Arduino IDE 1.6, I have version 1.8, and in the bottom it says the procedure works for Arduino 1.0.x software. And the image in the circuit is of Atmega168 but on searching I found https://www.arduino.cc/en/Hacking/PinMapping168, from which I infer 328 and 168 have same pin mapping ?.

What am I doing wrong? what do I need to change?

HELP!]1

EDIT

After enabling verbose it reports: "Device signature = 0x00ff00"


texts:
I've been trying to turn on 21W bulb with Protected MOSFETS.
But somehow the bulbs are getting high automatically from arduino.
I've tried all the hardware related things like pull down with different resistors, but no luck.
Is it possible due to separate ground of controller and Switch?
Because Switch and bulbs are powered through SMPS of 12V 10A while Arduino through Laptop USB cable.
Used this protected mosfet, circuit as given on page no 50 of datasheet.

Following is the code I used.

#include <TimerOne.h>

int LED = 13;
int IN0 = 12;
int IN1 = 11;
int OUT1 = 10;
int OUT2 = 9;
int OUT3 = 5;
int OUT4 = 7;
int OUT5 = 6;
int count = 0;

void setup() {
 pinMode(IN0, INPUT);
 pinMode(IN1, INPUT);
 pinMode(OUT1, OUTPUT);
 pinMode(OUT2, OUTPUT);
 pinMode(OUT3, OUTPUT);
 pinMode(OUT4, OUTPUT);
 pinMode(LED, OUTPUT);
 digitalWrite(OUT3, LOW);
 Timer1.initialize(1000000);
 Serial.begin(9600);

}

//void flash_R()
//{
//  digitalWrite(LED, !digitalRead(LED));
//  digitalWrite(OUT3, !digitalRead(OUT3));
//  //digitalWrite(OUT4, !digitalRead(OUT4));
//
//  if(digitalRead(LED)){
//    Serial.println("ON");
//  }
////  Serial.print("Count Value: ");
////  Serial.println(count++);
//}

void flash_L()
{
  //digitalWrite(OUT3, LOW);
  digitalWrite(LED, !digitalRead(LED));
  digitalWrite(OUT3, !digitalRead(OUT3));
  //digitalWrite(OUT4, !digitalRead(OUT4));

  if(digitalRead(OUT3)){
    Serial.println("hello");
    //Serial.print("Count Value: ");
    //Serial.println(count++);
  }
}

void loop() {
    Timer1.attachInterrupt(flash_L);
  }

  [1]: https://i.stack.imgur.com/64yyQ.jpg


texts: Selecting different arrays using a list of pointers

texts:
I have different arrays of different sizes, and a list of pointers to the addresses of each array. How do I select each array using the list of pointers, and access it's elements. On Teensy 3.2 board.

int * arr_list[3];
const int arr_sizes[3] = {3,4,5};  // array of the array sizes
const int ar1[3] = {12,2,8};       // arrays of  different sizes
const int ar2[4] = {41,3,6,47};
const int ar3[5] = {9,32,1,5,7};

void map_arrays(){          // list of pointers with the addresses of the
                            // arrays
arr_list[0] = (int*) &ar1;
arr_list[1] = (int*) &ar2;
arr_list[2] = (int*) &ar3;
};

int arr_number = 1;          // select array
int a = arr_sizes[arr_number];    // the size of the selected array
int *b = arr_list[arr_number];
int test = 0;

void setup() {

Serial.begin(57600);  //serial monitor

}

void loop() {

for (int i=0; i<a; i++) {     // for the selected arr_number iterate and
test = b[i];                  // return the index elements

}

Serial.println("size =");
Serial.println(a);
Serial.println();
delay(1000);
Serial.println("index =");
Serial.println(test);
Serial.println();
delay(500);

 }


texts:
I want to make a large clock, 16 inch x 7.5 inch, which will display dd Month yyyy.
What would be the best way to do this?
Does Arduino have a built in clock, and I'd just need logic to turn on/off LEDs on a display that already has dd Month yyyy? Do such displays exist which I can connect to Arduino?


texts: Replace digitalWrite with a selective bitwise operation

texts:
I have the following code with digitalWrite I aim to write with bitwise operation only.
No portability concerns here whatsoever. (for atmega328p here)

#define DATAOUT 11//MOSI
byte commandbits = B11000000;
for (int i = 7; i >= 3; i--) {
    digitalWrite(DATAOUT, commandbits & (1 << i));
}

I came up with something like this below which works.

#define DATAOUT 11//MOSI
byte commandbits = B11000000;
for (int i = 7; i >= 3; i--) {
    PORTB = (PORTB &(~(1<<3))) | (((commandbits &(1 << i))>>i) << 3);
}

Is this the most concise way. Is there a way to simplify it?


texts: Where do I find the enclosures for an Arduino and a bunch of sensors?

texts:
I recently started playing with Arduino in order to do several projects, including:

A system which will measure some characteristics of the indoor air and could alert me if something goes wrong (for instance if the percentage of CH4 goes beyond a threshold).
A system I can bring with me on a walk which will measure the pollution and other characteristics of the air outdoors.

While the quantity and the diversity of the sensors for such projects, as well as the ease of use is mind blowing, I'm blocked at one aspect: the casing. Both of the projects require to put the electronics within a plastic case with:

Enough space for not only Arduino, but also the sensors. Some, such as MQ2/MQ5, can be quite large.
Holes for air flow, which are large enough to let small particles, but small enough to keep insects and large dust out of the electronics.
A hole for an USB cable and possibly a hole for the LED.

Unfortunately, the popular sites selling Arduino-related stuff have practically nothing when it comes to the cases. In most cases, the choice is limited to (1) the enclosures for Arduino itself (or other boards), with no holes in them and (2) the multicolored modular systems which look like LEGO bricks.

Outside Arduino-related sites, the only idea I have is to buy somewhere an old smoke detector, throw away the electronics and put Arduino and the sensors inside. For now, most smoke detectors I've seen seem too small for the task, and have to be modified in order to accommodate the USB cable.

Am I missing something? How other people do when they need an enclosure which fits Arduino and sensors and doesn't look geeky?


texts: Externally Powering a 3.3V device (nRL24L01+) with a 5V Arduino Pro Mini?

texts:
I have seen several references where the solution to interfacing a 5V Arduino with a 3.3V nRF24L01+ was to power the nRF24L01+ externally.

How do I do this?  The ground of the nRF24L01+ is connected to the Arduino; can I simply attach 3.3V power between the power and ground pins of the nRF24L01+?


texts:
I am using two RFID sensors operating on SPI with arduino Due. They will not be operating at the same time.
Is it favorable to use the ICSP pins as SPI pins for one of them, or use them in a one master two slaves configuration with the SPI header?


texts: How to write a script if water sensor comes into contact with water for more than 2 mins and LED lights up

texts:
I am a newbie to arduino and programming. I would like to come out with a code for water sensor to detect the presence of water for more than 2mins before lighting up the LED lightbulb. Currently using Arduino, Grove baseshield with grove water sensor http://wiki.seeedstudio.com/Grove-Water_Sensor/.

I have the simple base code but not sure how do i go about adding in the function to detect water for a longer period of time before the light lights up:

#define watersensor 8               //Grove water sensor to Arduino Digital Pin 8
#define led 4                      //Grove LED to Digital Pin 4

int isWater;
bool wasWater = false;
//bool isWater, wasWater = false;    // true => currently we are not seeing water
uint32_t waterstart_ms = 0;        // time first saw water

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

void loop()
{
   // Is there water?
 isWater = digitalRead(watersensor);     // read sensor
 Serial.println(isWater);

   if( isWater ){
      if( wasWater ) {
      waterstart_ms = millis();  // First water: note the time
      }
        if( millis() - waterstart_ms >= 1*5*1000 ){// Water continues for 5s (trial first); time to light LED?
            digitalWrite(led, HIGH);
        }//end if
            wasWater = true;
   } // end first if
   else {
      wasWater = false; // No water; LED off
      digitalWrite(led, LOW);
   }
}


texts: Red LED not turning off on Adafruit Circuit Playground Classic

texts:
When using the traditional Blink example program, the light blinks as expected. Even when writing from scratch digitalWriteing pin 13 to high and low repeatedly works fine. The problem is when I try to use CircuitPlayground.redLED(false). That has no effect, and the Circuit Playground specific Hello_Blink example doesn't work at all. The LED is just constantly on no matter what I do.

I've looked through the source code for the CircuitPlayground library and it's also using pin 13, and doing essentially the same thing as the traditional blink program.

Not sure what else could be causing this.

This is the Blink sketch that's working:

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

And this is the Hello_Blink sketch that is not working (LED remains on permanently):

#include <Adafruit_CircuitPlayground.h>

void setup() {
  CircuitPlayground.begin();
}

void loop() {
  CircuitPlayground.redLED(HIGH);
  delay(500);
  CircuitPlayground.redLED(LOW);
  delay(500);
}

Changing HIGH and LOW to true and false does nothing.

I also have noticed two other strange things. The speaker does an audible click when the board resets when using the Hello_Blink sketch (or any other sketch that uses the CircuitPlayground library), as if pin #5 is being held high as well. Also, I added these two lines

pinMode(6, OUTPUT);
digitalWrite(6, HIGH);

to the setup() of both programs and then probed #6 with a multimeter. Pin #6 is not connected to anything. The traditional blink program allows the pin to go high as expected. The CircuitPlayground sketch, however, the pin stays low.

I am using this library with a atmega32u4.


texts: LED Blink in assembly with timer1 output compare interrupt not working

texts:
I was trying to have some fun with avr-assembly on my arduino and I tried the following codes to blink my LED
first I tried the ISR approach and when It didn't work I tried the CTC mode one,
both codes are listed respectively. on the first one the LED lightsup and stay that way (no blinking) on the second one it just stays off
one more thing to note is on trying to load OCR1AL first The led would blink nicely if my hand got near PORTD pins for some reason,
I guessed it's some grounding problem and It's fixed when I pulled high all PORTD pins and it disappeared completely when I figured out that I need to load (the high byte) OCR1AH first
.nolist
.include "m328Pdef.inc"
.list

.org    0x0000
jmp     Init

.org    0x0016
jmp     TIMER1_COMPA

.EQU    LED_PIN = PB1

Init:
    ;ldi    r16, 255
    ;out        DDRD, r16
    ;out    PORTD, r16

    ;First configure The led pin as output and initilize it to high
    sbi     DDRB, LED_PIN
    sbi     PORTB, LED_PIN

    ;Second Enable Global Interrupts
    sei

    ;Enable the Output compare Interrupt in the TIMSK1 Register
    ldi     r16, 0b00000010
    sts     TIMSK1, r16

    ; Reset the TCCR1A
    ldi     r16, 0b00000000
    sts     TCCR1A, r16

    ; Set the prescalar to 256 in the Timer Control 1B register
    ldi     r16, 0b00000111
    sts     TCCR1B, r16

    ;Now load the value for Output compare register 31250 or   01111011 00100000  or 15625 =  00111101 00001001
    ldi     r16, 0b00111101
    ldi     r17, 0b00001001
    sts     OCR1AH, r16
    sts     OCR1AL, r17

LOOP:

    rjmp    LOOP

TIMER1_COMPA:
    ;First Reset the coutner
    ldi     r16, 0
    sts     TCNT1H, r16
    sts     TCNT1L, r16

    ;Second Toggle the Pin (LED) state
    sbi     PINB, LED_PIN

    reti

CTC:
.nolist
.include "m328Pdef.inc"
.list

.org    0x0000
jmp     Init

.org    0x0016
jmp     TIMER1_COMPA

.EQU    LED_PIN = PB1

Init:
    ;ldi    r16, 255
    ;out        DDRD, r16
    ;out    PORTD, r16

    ;First configure The led pin as output and initilize it to high
    sbi     DDRB, LED_PIN
    sbi     PORTB, LED_PIN

    ;Second Enable Global Interrupts
    sei

    ;Enable the Output compare Interrupt in the TIMSK1 Register
    ldi     r16, 0b00000010
    sts     TIMSK1, r16

    ; Reset the TCCR1A
    ldi     r16, 0b01000000
    sts     TCCR1A, r16

    ; Set the prescalar to 256 in the Timer Control 1 registers
    ldi     r16, 0b00001111
    sts     TCCR1B, r16

    ;Now load the value for Output compare register 31250 or   01111011 00100000  or 15625 =  00111101 00001001
    ldi     r16, 0b00111101
    ldi     r17, 0b00001001
    sts     OCR1AH, r16
    sts     OCR1AL, r17

LOOP:
    rjmp    LOOP

TIMER1_COMPA:
    ;First Reset the coutner
    ;ldi    r16, 0
    ;sts    TCNT1H, r16
    ;sts    TCNT1L, r16

    ;;Second Toggle the Pin (LED) state
    ;sbi        PINB, LED_PIN

    reti


texts: How to transmit Float sensor values via NRF24L01 module?

texts:
I'm trying to figure out a way to transmit four sensor values: Voltage, Current, Power and consumption but I'm unable to do that.
Yet, my syntax is correct... what am I missing?

#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include <RF24.h>

#define ACS712 A0

int lastData = 0;
int dataSum = 0;
int Count = 0;

float Voltage;
float Current;
float Power;
float kWh;
float Consumption;
String Data;

float vpc = 4.882813; // approx. voltage per count

RF24 radio(9, 10); // CE, CSN
const byte addresses[][6] = {"00001", "00002"};

void setup() {
  Serial.begin(115200);
  pinMode(13, OUTPUT);
  radio.begin();
  radio.openWritingPipe(addresses[1]); // 00001
  radio.openReadingPipe(1, addresses[0]); // 00002
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}

void loop() {

  radio.stopListening();

  if (millis() > lastData + 1) {
    dataSum += sq(analogRead(ACS712) - 512);
    Count++;

    lastData = millis();
  }
  // If statement to make calculations.
  if (Count == 1000) {

    // To get the RMS of the data.
    float mean = dataSum / Count;
    float value = sqrt(mean);

    // To get the Voltage (in volts) consumed.
    float Voltage = value * vpc;

    // To get the Current (in amps) consumed.
    float Current = Voltage / 66;

    // To get the Power (in watts) consumed.
    float Power = Current * 240;

    float kWh = Power / 1000;
    float Consumption = kWh;

    dataSum = 0;
    Count = 0;

    Data += F("\nVoltage: ");
    Data += String(Voltage, 3);
    Data += F("\nCurrent: ");
    Data += String(Current, 3);
    Data += F("\nPower: ");
    Data += String(Power, 3);
    Data += F("\nConsumption: ");
    Data += String(Consumption, 3);
    //Serial.println(Data);

    radio.write(&Data, sizeof(Data));
    if (radio.write(&Data, sizeof(Data)) && true) {
      Serial.println("Sent!");
    } else {
      Serial.println("Failed!");
    };
    delay(10);
  }
}


texts: Reading from a KY-040 rotary encoder with Digispark

texts:
I have a rotary encoder KY-040 connected to a Digispark like this:

CLK go to p0 and and DT go to p2, SW is disconnected for now (it's just a button).

I did everything like the instructions here: http://henrysbench.capnfatz.com/henrys-bench/keyes-ky-040-arduino-rotary-encoder-user-manual/

#include <DigiKeyboard.h>

 int pinA = 0;  // Connected to CLK on KY-040
 int pinB = 2;  // Connected to DT on KY-040
 int encoderPosCount = 0;
 int pinALast;
 int aVal;
 boolean bCW;

 void setup() {
   pinMode (pinA,INPUT);
   pinMode (pinB,INPUT);
   /* Read Pin A
   Whatever state it's in will reflect the last position
   */
   pinALast = digitalRead(pinA);
   Serial.begin (9600);
 }

 void loop() {
   aVal = digitalRead(pinA);
   if (aVal != pinALast){ // Means the knob is rotating
     // if the knob is rotating, we need to determine direction
     // We do that by reading pin B.
     if (digitalRead(pinB) != aVal) {  // Means pin A Changed first - We're Rotating Clockwise
       encoderPosCount ++;
       bCW = true;
     } else {// Otherwise B changed first and we're moving CCW
       bCW = false;
       encoderPosCount--;
     }
     Serial.println("Rotated: ");
     if (bCW){
       //Serial.println ("clockwise");
       DigiKeyboard.sendKeyStroke(KEY_V); //or DigiKeyboard.write("1");
     }else{
       //Serial.println("counterclockwise");
        DigiKeyboard.println("cc");
     }
     Serial.print("Encoder Position: ");
     Serial.println(encoderPosCount);

   }
   pinALast = aVal;
 }

I only changed the pin numbers in the code and the Serial.println (... to any of the following:

DigiKeyboard.write("1");
DigiKeyboard.println("1");
DigiKeyboard.sendKeyStroke(KEY_V);

All of them didn't do anything when rotating the knob...

Any ideas?
Maybe the 10K resistors are too much?


texts:
I can't seem to find the error I made; can anyone help me?
The error message: 'Servo_Pointer' was not declared in this scope
I get the error at the end of the code with the line: Servo_Pointer.write(servo_pos)
The code:
const int photo_left = A0;    // select the input pins for the photoresistor
const int photo_right = A1;
const int ledPin_1 = 2; // These leds will be used for the testing of the pointing of the servo motor
const int ledPin_2 = 4;
const int ledPin_3 = 7;
const int ledPin_4 = 8;
const int ledPin_5 = 12;
const int photoValue = 0;  // variable to store the value coming from the photoresistor
const int numReadings = 10;
int readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(ledPin_1, OUTPUT);
  pinMode(ledPin_2, OUTPUT);
  pinMode(ledPin_3, OUTPUT);
  pinMode(ledPin_4, OUTPUT);
  pinMode(ledPin_5, OUTPUT);
  Serial.begin(9600);
  #include <Servo.h>
  Servo Servo_Pointer;
  Servo_Pointer.attach(9);
  int servo_pos = 0;
  // initialize serial communication with computer:
  Serial.begin(9600);
  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading  ) {
    readings[thisReading] = 0;
  }
}

void loop() {
  Servo_Pointer.write(servo_pos); // tell servomotor to go to position in variable 'servo_pos'
  delay(15);          // waits 15ms for the servo to reach the position
  // turn the ledPin on
  delay(15);
}


texts: Integrating Java program with arduino mega is it possible?

texts:
I have just written a java algorithm to get a chess move when a chess move is inputted in SAN notation the algorithm used : Monte Carlo. Is it possible to integrate this program with an Arduino mega and How?

My mega will be getting inputs from a sensory board and I want to send these inputs to the java program without using any additional board.

Note:
By integrate I mean that the Java program should run in the Arduino mega itself

Can anyone suggest a solution?


texts: Help with a function that accepts different parameter types

texts:
I'm trying to create a function that prints out an XML tag with a value. I have the code below, but kind of stuck. I'd like to be able to call the function, and pass a value that could be a float, int, string or char. Appreciate any help.

char PingTime[6] = "3ms";
char PingText[60] = "ping reply blah blah";
float humidity = "40.56";
int DigialPin = 0;

PrintXMLTag(cl,"pingtime",PingTime);
PrintXMLTag(cl,"PingText",PingText);
PrintXMLTag(cl,"humidity",humidity);
PrintXMLTag(cl,"DigialPin",DigialPin);

void PrintXMLTag_DEC(EthernetClient cl, const char* tag, NotSure?? val)
{
  char tmp [100];
  StrClear(tmp,100);

  // If val type is float ----------------------
  int d1 = val; // Get the integer part
  float f2 = val - d1; // Get fractional part
  int d2 = trunc(f2 * 10000);// Turn into integer
  sprintf(tmp,"<%s>%d.%02d</%s>\n",tag,d1,d2,tag);
  // end float

  // If val type is string ----------------------

  // If val type is int ----------------------

  // If val type is char ----------------------

  cl.print(tmp);
}

Update, now converting the type to char before calling the PrintXML function resolves my initial issue. If I use the code below it seems to chew up a lot of memory, is there something obviously wrong? As a workaround I'm just printing the XML tags using cl.print and the memory usage is stable.

void PrintXMLTag(EthernetClient cl, char* tag,  char* val)
{
  char tmp [100];
  sprintf(tmp,"<%s>%s</%s>\n",tag,val,tag);
  cl.print(tmp);
  StrClear(tmp,100);
}


texts: Establishing an MQTT connection using Arduino Mega and ESP8266

texts:
As the title says, I want to send MQTT messages to a server using ESP8266 with an Arduino Mega as controller, but so far, every library that I have found is based on Ethernet. I don't want Ethernet, I want WiFi, so those solutions don't work for me.
I have tried using PubSubClient library, but the problem is that to create an instance (PubSubClient client(?????)), I have to set a client. What should I put in there? Is there another library I must use?


texts:
at once, when i connect arduino uno to my computer, my computer shuts down, after that i cannot upload programs to my computer,the board is not working but the led is ON. Before this, i upload programs 4 to 5 times continuously. i upload program with no physical connections in arduino except motor shield which is also not connected to anything.
i used three boards, all of them got damaged.

my computer's USB port and USB cable is in good codition.
i already updated my drivers.

computer spec: dell inspiron 15 3567
               windows10 x64 bit


texts: Need help with a program for a button to change the display on an OLED display

texts:
So I am programming an OLED display from my Arduino Uno. I am trying to have a button that switches the different words on the display. (The words are just placeholders for programs as of now.) My program has a button that changes a counter, and an if test to see what the counter is so it can display the appropriate word. The problem is, whenever I press the button, the display turns black and doesn't do anything anymore. When I start/reset the Arduino, it displays TEMPERATURE, but it should say TIME.

#include <OLED_I2C.h>

OLED  myOLED(SDA, SCL, 8);

extern uint8_t SmallFont[];
extern uint8_t MediumNumbers[];
extern uint8_t BigNumbers[];

//constants:
const int buttonPin = 2;

//variables:
byte oldButtonState = HIGH;
int screenNumber = 0;
byte buttonState = 0;

void setup()
{
  myOLED.begin();
  myOLED.setFont(SmallFont);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop() { //myOLED.print formats with (string, text_placement,     pixel_location)
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  // Test if the button is being pressed
  if (buttonState == HIGH) {
    myOLED.clrScr();
    myOLED.update();
    oldButtonState = buttonState;
    if (screenNumber != 2) {
      ++screenNumber;
    }
    else {
      screenNumber = 0;
    }
    //delay a little to avoid bouncing
    delay(200);
    }

  //Test for the screenNumber variable and change to the
  //according screen
  if (screenNumber == 0) {
    myOLED.print("TIME", CENTER, 16);
    myOLED.update();
  }
  else if (screenNumber == 1) {
    myOLED.print("TEMPERATURE", CENTER, 16);
    myOLED.update();
  }
  else if (screenNumber == 2) {
    myOLED.print("DIRECTION", CENTER, 16);
    myOLED.update();
  }
  else {
    myOLED.print("ERROR", CENTER, 16);
    myOLED.update();
  }
}


texts: How can I load fonts into Adafruit GFX for TFT display (ILI9341)

texts:
I get a compile error when I try to set a different font in Adafruit GFX on a TFT display on my Arduino Uno.

I'm testing a new TFT shield for Arduino equipped with an ILI9341 by using the Adafuit GFX libraries and examples. The test program supplied with the library works fine out of the box displaying text and all kind of drawings on the screen.

However, the standard font built into the Adafruit GFX library is "blocky" to save memory space. They do provide other fonts, but I get an error when I try to invoke them.

The segment of code that throws the compile error is this one:

unsigned long testText1() {
  tft.setFont();    // When I remove this line the sketch compiles OK
  tft.fillScreen(BLACK);
  tft.setCursor(0, 50);
  tft.setTextColor(RED);
  tft.setTextSize(13);
  tft.println("1234");
}

When compiling I get this error:

  "error: ‘class Adafruit_ILI9341_8bit_AS’ has no member named ‘setFont’"

According to Adafruit's GFX manual, the setFont() procedure allows to define a new font or revert to the standard one.

I examined the libraries and nowhere could I find a procedure to select a font, yet the example has declarations like these below, so changing fonts should be possible:

#include <Adafruit_GFX_AS.h>
#include <Adafruit_ILI9341_8bit_AS.h>
#include <Font16.h>
// #include <Font32.h>
// #include <Font64.h>
// #include <Font72.h>
#include <Font7s.h>
#include <Load_fonts.h>

I would like to load the 7segment font with:

tft.setFont(&Font7s);

Does anybody have experience to share loading these fonts?


texts:
I want to open a solenoid valve with an arduino, and have set up the following circuit

The plan is to add solenoids to every relay on the board. I am wondering if this circuit is any useful, or if there are major flaws present. I am worried about frying my components, especially the 12V 2A hooked up with a solenoid of 1A, however i want the 2A, since i want to be able to power multiple solenoids at the same time.

I tried switching the board directly from the arduino, and with its 5V to the VCC, but it was not enough to make the relays switch, maybe a transistor is in line, if so, which one?


texts: Cat motion detector that can tell the difference from humans

texts:
I'm trying to build a cat motion detector but, to avoid getting false alarms when a person walks by, I was thinking of using RFID. i.e. the cat has a collar and the detector senses the collar when they get within a couple of feet and makes a noise.

The problem there seems to be with RFID is that the range is so short - e.g. 4".

Anyone have a better solution?


texts: Posting data to ASP web service from GSM using AT commands - where am I going wrong

texts:
I'm using an Arduino uno with a SIM900 GSM shield.  I'm trying to connect the Arduino to my (ASP MVC) website.  I've written an API which i've successfully tested with postman, and whilst the GET Command works fine, I've had no success with POSTING data as yet.  Using the arduino to echo serial monitor input, I've done the following...

So, some setup commands

    AT+CGATT?
    AT+SAPBR=3,1,"CONTYPE","GPRS"
    AT+SAPBR=3,1,"APN","internet"    (vodafone UK parameters
    AT+SAPBR=3,1,"USER","web"
    AT+SAPBR=3,1,"PWD","web"
    AT+SAPBR=1,1
    AT+SAPBR=2,1     (confirms i have an IP address)

i then do the following...

    AT+HTTPINIT
    AT+HTTPPARA="CID",1
    AT+HTTPPARA="PROIP","212.183.137.12"   (vodafone uk proxy settings)
    AT+HTTPPARA="PROPORT","8799"
    AT+HTTPPARA="CONTENT","application/json"
    AT+HTTPPARA="URL","http://mywebsite.co.uk/api/obs"
    AT+HTTPDATA=83, 10000    (gives the download command).
    {"SensorName": "TestSensor", "ObsValue": 31, "ObsDateTime": "2017-10-01T03:30:00"}
    AT+HTTPACTION=1

and I just get an "OK" back, no httpaction response, and no data stored on the database.

Is there anything I'm doing that is obviously wrong?  Does HTTPACTION come before the data?

Are there commands I can use to check the status of my http session on the GSM board? to confirm that my settings are correct?

Finally, I keep getting messages like

    +CREG: 1,"002A","0F48"

Always the 1 (presumably the CID i'm using), and always the 002A, but the final part varies.

Any help would be hugely welcome.  Thanks.


texts:
Me and my friend have a project to do and we can't seem to figure out why the code we used for our Arduino Nano Board isn't compiling giving us the Expected ')' before ';' token Error

Here is the code:

// connect motor controller pins to Arduino digital pins
// motor one
int enA = 10;
int in1 = 9;
int in2 = 8;
// motor two
int enB = 5;
int in3 = 7;
int in4 = 6;

void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}
void demoOne()
{
  // this function will run the motors in both directions at a fixed speed
  // turn on motor A
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enA, 200);
  // turn on motor B
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enB, 200);
  delay(2000);
  // now change motor directions
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(2000);
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}
void demoTwo()
{
  // this function will run the motors across the range of possible speeds
  // note that maximum speed is determined by the motor itself and the operating voltage
  // the PWM values sent by analogWrite() are fractions of the maximum speed possible
  // by your hardware
  // turn on motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  // accelerate from zero to maximum speed
  for (int i = 0; i ; 256; i++)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // decelerate from maximum speed to zero
  for (int i = 255; i (&gt);= 0; --i)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}
void loop()
{
  demoOne();
  delay(1000);
  demoTwo();
  delay(1000);
}

We could really use some help.


texts: Can the Arduino Eclipse plugin use the libraries installed by the Arduino IDE?

texts:
In Arduino Eclipse (v3, nightly build) I have not been able to load 'foreign' libraries, those written by me or someone else, so they are not among the available choices in the include-library dialogs.

I've tried adding them to a project as well as adding them as an available library resource using the built-in dialogs for doing so, but I don't see a way to select a library that isn't already included in those dialogs.

My ideal case would be a way for the Arduino Eclipse plugin to use the same boards and libraries as I use in my Arduino IDE installation, so that:

An upgrade to the Arduino IDE would simultaneously upgrade the core libraries in Eclipse;
An optional library would need installing in only one place;
Modifying an optional library would only need to be done once, in one place.

The goal, as in an earlier question of mine, is to seamlessly permit using either IDE to advance a project. However, I'd be grateful to be able to add to my Eclipse installation any library of my choosing.


texts: Servotimer2.h is not recognised as a library by arduino uno

texts:
I'm doing a project for school with an arduino uno. I want to control a motor using a RF-module as remote control. I need the library Virtualwire.h to use the RF-module and the library Servo.h to control the motor. I downloaded the library Servotimer2.h because Virtualwire.h and Servo.h both want to use timer 1 of the arduino. I added this library to arduino libraries but arduino doesn't recognise it as a library when I include it to my program.
can someone help me with this issue? I tried to find a solution but can't find it.
Many thanks allready!


texts: Arduino Nano/Uno and js sketch compiling/uploading from browser

texts:
I need to compile generated source code in js runtime then upload it to my device.

Compiling:

I have found arduino-cli

Uploading:

There is only avrgirl but it doesn't work in browser. What should I do?


texts: Why does using ESP8266 in deep sleep mode still drain the battery quickly?

texts:
I've made a "weather station" using the ESP8622. To save battery I'm using sleep mode but still the battery is drained after a couple of days. According to this post it should last at least a year.

I haven't done any measurements yet, wanted to know if there's something obvious that I've missed that could explain why the battery is drained so quickly? Attaching code and an image showing the hardware setup.

#include "DHT.h"
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#define DHTPIN D2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

const char* ssid     = "xxxx";
const char* password = "xxxx";

const char* host = "xxxx";

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

  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  readSensorsAndPost();
  ESP.deepSleep(18e8); //30 minutes
}

void readSensorsAndPost() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  char charVal[10];
  dtostrf(t, 5, 2, charVal);
  makeAnHttpRequest(charVal);
}

bool makeAnHttpRequest(String msg) {
  //send the value
}

void loop() {

}


texts: How to manage interrupt from accelerometer BMA220?

texts:
I would like to use the interrupt register from the BMA220 accelerometer in order to detect high-g shock. I am using a Mega2560 and the sensor is powered by 3.3 V. I use a voltage divider to convert the 5V from the card to 3.3V because the 5V pin gives more current. The memory map concerning the registers is shown below
In the datasheet the section concerning high-g registers is as followed :

It is written that whenever a condition is met for the interrupt controller "an interrupt (logic '1') is issued through the INT pin of the sensor."

However after initializing the necessary registers (in I2C):

0xC for high_th
0xA for high_hy and high_dur
0x1C for en_high_x/y/z

I don't get my interrupt working. Using a voltmeter I always get a high value (3.3V) on the INT pin of my accelerometer eventhough it stays still and I wrote a threshold of 2G...

Here is the code I am using :

#include <BMA220.h>
#include "SEN0168.h"

BMA220 bma;
byte interruptPin = 2;
byte count = 0;
const uint8_t HIGH_SET = 0xA;
const uint8_t HIGH_LOW_TH = 0xC;
const uint8_t INTERRUPT_REG = 0x18; // to get the bit indicating an interrupt was detected, not used because of the INT pin
const uint8_t ENABLE = 0x1C;

void setup() {
   Serial.begin(74880);
   pinMode(interruptPin, INPUT);
   init_SEN0168(R4); // set sensitivity to 4G
   bma.setRegister(ENABLE, 0xF7); // enable high-g-detection, reset interrupt bit control and latch permanently
   bma.setRegister(HIGH_LOW_TH, 0x1); // Threshold of 1G
   bma.setRegister(HIGH_SET, 0x1); // No hysteresis and 2 signals needed to trigger
   attachInterrupt(digitalPinToInterrupt(interruptPin),counter, HIGH);
}

void loop() {
    if (count==1){
    Serial.print("x-axis: ");
    Serial.println(accel_range_SEN0168(X,R4));
    Serial.print("y-axis: ");
    Serial.println(accel_range_SEN0168(Y,R4));
    Serial.print("z-axis: ");
    Serial.println(accel_range_SEN0168(Z,R4));
    count =0;
    bma.setRegister(INTRP_RES_REG, 0xF7); // enable high-g-detection, reset interrupt bit control and latch permanently
    }
    else{
      Serial.println("No shock");
      count =0;
    }
}

void counter(){
  count +=1;
}

Am I missing something to clear in one register ? Or maybe since the card is in 5V and the sensor 3.3V logic there is a problem to detect change on the interrupt pin ?  Also I don't know if I understand properly the "logic 1". For me it means it puts the pin to "HIGH".

I use a part of the library written by Sönke Carstens-Behrens to set the registers from here : https://github.com/scbrac/BMA220.

I really need this interrupt pin to work...

Thank you for your help !


texts:
Pardon the double post, but I'm not getting much traction with this question over at arduino.cc so I'm looking for answers here now.

Original post: http://forum.arduino.cc/index.php?topic=391698.0

  I get the idea of uploading a "stop" sketch for the purpose of
  overriding a previously uploaded program in Flash memory space.

  Then of course we have EEPROM for "long-term" storage.

  However, let's say an Arduino: Read user input as secret key and store
  in memory (SRAM) Performed a signing operation with secret key
  Subsequently powered off

  We know that computers introduce a wide range of complications to
  security because data can still be recovered, even after being erased
  or overwritten in some cases, variables stored in memory float around
  (unless pinned for decryption in SecureString contexts, etc.), etc.

  To establish context for the following questions, let's [overly]
  simplify the attack vector in saying this would be a scenario where an
  Arduino used in a security application is physically disconnected,
  stolen, and then powered on sometime later.

  Question 1: Obviously we're not talking about storing keys on disk
  necessarily (i.e. EEPROM). How likely (or difficult) would it be to
  analyze SRAM with the intent to recover keys that may have been
  previously stored in memory?

  Question 2: Similarly, let's say sensitive information was in fact
  stored in EEPROM.  Does the same hold true of data previously stored
  in EEPROM that has since been overwritten with new (i.e. zero) data?

Any help would be greatly appreciated. Thanks!


texts:
sim.println("AT+CMGS=\"+91xxxxxxxxxx\"\r");
I don't want to write this. I want to write mobile number on serial monitor in Arduino and on that number, i want to send message. how can I do?


texts: Two Identical Potentiometers, two different results

texts:
quick question.  I have two 10 turn precision potentiometers and I tested both when I bought them a few weeks ago, both worked as expected.  However now that I have epoxied one of them into my project and wired it up, I don't get any resistance.  I get a max reading all the time regardless of where the dial is set.  So then I pull off the wiring and do the same setup with the other potentiometer and I am still getting expected results.

What could be the reasoning for the sudden difference in readings? Could the first one have gone bad, and if so how often does this happen and how can I avoid it in the future?

Everything falls within recommended specs of the pot and neither has been really used at all.


texts:
I am working on an arduino mega 2560 sketch.
I have to parse http query strings.

My program is concatenating strings for each http request.
And i have an http request every second during all day.

I have read that this kind of work may cause ram memory fragmentation. I am very upset about this because my program will randomly crash if there are no free ram memory.

Do you know if there is a way to initialise a string with a given memory length ?

I do not want to work with char arrays because i need indexof, substring functions and comparison with ==

Thanks


texts: My software serial code won't work at > 4800bps

texts:
I've put together a simple software serial (send-only) implementation for use on my attiny8[45] microcontrollers.  I realize that there are more efficient USI-based implementations out there; this was mostly an educational exercise.  The code uses TIMER0 in CTC mode to time the sending of bits on an available output pin.

It works fine from 300bps up to 4800bps, but anything faster than that just results in garbage.

The complete code is at the bottom of this answer.    The following settings all work correctly:

4800bps

#define BPS 4800
#define SCALE_FLAG 1
#define SCALE_VAL 1

2400bps

#define BPS 2400
#define SCALE_FLAG 2
#define SCALE_VAL 8

1200bps

#define BPS 1200
#define SCALE_FLAG 2
#define SCALE_VAL 8

300bps

#define BPS 300
#define SCALE_FLAG 3
#define SCALE_VAL 64

While this fails:

9600bps

#define BPS 9600
#define SCALE_FLAG 1
#define SCALE_VAL 1

Because everything other than 9600bps works I'm tempted to think that my code is correct, and yet I expect that I should be able to achieve 9600bps with these microcontrollers.

Are there any obvious bugs in this code? I think that's the most likely explanation, but after poking at this for a couple of days I'm not seeing it.

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/atomic.h>
#include <string.h>

#define BPS 9600
#define SCALE_FLAG 1  // This is the value that goes in the TCCR0B register
#define SCALE_VAL 1   // This is the divisor selected by SCALE_FLAG

#define TXPORT PORTB
#define TXDDR DDRB
#define TXPIN PORTB0

#define TICKS_PER_BIT (F_CPU/BPS/SCALE_VAL)
#define mS_PER_BIT (1000000/BPS/1000)
#define uS_PER_BIT ((1000000 / BPS) - (1000 * mS_PER_BIT))

typedef struct SERIAL_PORT {
    uint8_t data;
    uint8_t index;
    uint8_t busy;
} SERIAL_PORT;

void millis_init();
uint32_t millis();

void serial_init();
void serial_putchar(char c);
void serial_print(char *s);
void serial_println(char *s);
void delay(uint32_t m);

volatile SERIAL_PORT port;
volatile uint32_t _millis,
         _micros = 1000;

int main() {
    millis_init();
    serial_init();
    while (1) {
        serial_println("hello world");
        delay(500);
    }
}

void delay(uint32_t m) {
    uint32_t t_start = millis();
    while (millis() - t_start < m);
}

void millis_init() {
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
        _millis = 0;
    }
}

uint32_t millis() {
    uint32_t x;
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
      x = _millis;
    }
    return x;
}

void serial_init() {
    DDRB |= 1<<TXPIN;       // Set TXPIN as an output
    TXPORT |= 1<<TXPIN;     // Set TXPIN high (serial idle)
    TCCR0A = 1<<WGM01;      // Select CTC mode
    TCCR0B = SCALE_FLAG;    // Set clock scaler
    OCR0A = TICKS_PER_BIT;  // Set CTC target value
    TIMSK0 |= 1<<OCIE0A;    // Enable compare match interrupt
    sei();
}

void serial_putchar(char c) {
    while (port.busy);
    port.data = c;
    port.index = 0;
    port.busy = 1;
}

void serial_print(char *s) {
    while (*s) serial_putchar(*s++);
}

void serial_println(char *s) {
    serial_print(s);
    serial_putchar('\r');
    serial_putchar('\n');
}

ISR(TIM0_COMPA_vect) {
    if (port.busy) {
        switch(port.index) {
            case 0:
                // send start bit
                TXPORT &= ~(1<<TXPIN);
                break;
            case 9:
                // send stop bit
                TXPORT |= (1<<TXPIN);
                port.busy = 0;
                break;
            default:
                // send data bit
                if (port.data & 1) {
                    TXPORT |= 1<<TXPIN;
                } else {
                    TXPORT &= ~(1<<TXPIN);
                }
                port.data >>= 1;
                break;
        }
        port.index++;
    }

    _millis += mS_PER_BIT;

    if (uS_PER_BIT > _micros) {
        _millis++;
        _micros = 1000;
    } else {
        _micros -= uS_PER_BIT;
    }
}


texts: How to connect an Arduino and a WAMP server's MySQL database?

texts:
I'm trying to connect an Arduino Mega to my WAMP server's database using MySQL connector for attendance logging. But it shows "Connection failed".

What is my WAMP server's IP address?

I connect my laptop and Arduino with a router so:

My laptop is 192.168.1.2
My Arduino is 192.168.1.3

I think this is correct.

/*
  MySQL Connector/Arduino Example: basic insert
  This example demonstrates how to issue an INSERT query to store data in a
  table. For this, we will create a special database and table for testing.
  The following are the SQL commands you will need to run in order to setup
  your database for running this sketch.

  CREATE DATABASE test_arduino;
  CREATE TABLE test_arduino.hello_arduino (
    num integer primary key auto_increment,
    message char(40),
    recorded timestamp
  );

  Here we see one database and a table with three fields; a primary key that
  is an auto_increment, a string, and a timestamp. This will demonstrate how
  to save a date and time of when the row was inserted, which can help you
  determine when data was recorded or updated.

  INSTRUCTIONS FOR USE

  1) Create the database and table as shown above.
  2) Change the address of the server to the IP address of the MySQL server
  3) Change the user and password to a valid MySQL user and password
  4) Connect a USB cable to your Arduino
  5) Select the correct board and port
  6) Compile and upload the sketch to your Arduino
  7) Once uploaded, open Serial Monitor (use 115200 speed) and observe
  8) After the sketch has run for some time, open a mysql client and issue
     the command: "SELECT * FROM test_arduino.hello_arduino" to see the data
     recorded. Note the field values and how the database handles both the
     auto_increment and timestamp fields for us. You can clear the data with
     "DELETE FROM test_arduino.hello_arduino".

  Note: The MAC address can be anything so long as it is unique on your network.

  Created by: Dr. Charles A. Bell
*/

#include <Ethernet.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(192, 168, 1, 3); // IP of the MySQL *server* here
char user[] = "root"; // MySQL user login username
char password[] = ""; // MySQL user login password

// Sample query
char INSERT_SQL[] = "INSERT INTO test_arduino.hello_arduino (message) VALUES ('Hello, Arduino!')";

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(115200);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);
  Serial.println("Connecting...");
  if (conn.connect(server_addr, 3306, user, password)) {
    Serial.println("Connected Successfully...");
    delay(1000);
  } else
    Serial.println("Connection failed.");
}

void loop() {
  delay(2000);
  Serial.println("Recording data.");
  // Initiate the query class instance
  MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
  // Execute the query
  cur_mem->execute(INSERT_SQL);
  // Note: since there are no results, we do not need to read any data
  // Deleting the cursor also frees up memory used
  delete cur_mem;
}


texts:
I have Arduino UNO board. Can I upload programs written in Lua?
I wrote a code for simple home automation using relays to control lights and tried to upload it to my Arduino board, I get error code of "Error compiling for board Arduino/Genuino Uno"? What does this mean?

This is the code I used:

var("Switch", "ME.BI21")
var("Relay", "ME.BO21")
var("RelayState", "ME.BO41")

RelayState = 1

Relay = Switch

if (Relay == 1 then){
  print("The Relay is ON")
}
else{
  print("The Relay is OFF")
}
end


texts: GUI interface with microcontroller to control a device through SPI

texts:
I am trying to develop a GUI to control a device hooked up on the Arduino. The Arduino communicates with the device through SPI. I have developed a GUI on MATLAB to visualize read by the Arduino. For this, I made Arduino write data from the MISO line to the serial port and MATLAB would read from the same port and do its magic. However, I am trying to come up with a method to write to the MOSI line using the GUI.

Right now I am thinking of making Arduino listen for a particular code (like a character) on the serial port and once it sees it, it will look for an x number of succeeding bytes. The bytes will be formatted in a particular way so that Arduino can then parse it and write to the appropriate registers.

Is there a better way to do this? As a generic question, what's a good way to write to a device hooked onto a microcontroller using I2C or SPI through a GUI?


texts: Save joystick movement and run a servo motor

texts:
I am planning to use a joystick to input joystick stroke directions, save the directions as number in a variable. The idea is to start a servo motor if the directions match the directions in the sketch.
for example, let us say, I perform the following movement on the joystick:
1. two left movement along x axis ( <-, <-)
2. two right movement along x axis ( ->, ->)
3. One Up movement along y axis
and 4. one down movement along y axis.
These movements are as a result of a user solving a clue. (two left strokes could mean an alphabet 'A' or a number 1, not decided yet, and so on..)

I would like to save the 4 or 5 joystick directions in a variable and if it matches the directions declared in the sketch (True condition), then DC servo motor would start and pull a screen up, which will expose 'SOLVED' written behind the screen.

Hope the scenario is clear. Since, I am new to this, I would like to get some help with the sketch and the connections (Arduino Joystick inputs and DC server output are available on web, it will be helpful if someone can give an overall guidance as well.


texts:
In the past I declared variables inside the main loop which worked just fine.
In a new project I did the same:

void loop(void)
{
    uint8_t counter;
    ....
    if (buttonPress)
        counter = 0;
    ...
    if (someCondition == true)
    {
        Serial.println(counter);
        counter++
    }
}

But then the output of the variable counter shows that for some reason the counter variable is reset to 0 instead of counting up. This happens even after the button is released.

The scope of the variable counter is the main loop and I just assumed that it will keep its value and count up.

What might be the reason for this variable to reset to 0?
Is it that other functions are called within the main loop?
Is it that an interrupt handler is called every now and then?

The solution I've found is to declare the variable as static:

static uint8_t counter;

Then it increments as expected.

Even though I've found a solution I'd really like to understand what the problem with my first approach was.


texts: How to remove the program from arduino board which is already there in it.?And I need that program in my arduino IDE how to take it please help me?


texts: ESP 8266 making noise signals to led matrix

texts:
I'm building ESP8266 led matrix project, but my ESP sometimes makes some kind of noise that makes random pixels on the matrix light in all different colors. It seems to be random. Does someone know why is that and how to solve it?
My code:
#include <ArduinoJson.h>
#include <Adafruit_GFX.h>
#include <Adafruit_NeoMatrix.h>
#include <Adafruit_NeoPixel.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>
#ifndef PSTR
 #define PSTR // Make Arduino Due happy
#endif

#define PIN 12
StaticJsonDocument<2500> response;

Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(16, 16, PIN,
  NEO_MATRIX_TOP     + NEO_MATRIX_RIGHT +
  NEO_MATRIX_ROWS + NEO_MATRIX_ZIGZAG,
  NEO_GRB            + NEO_KHZ800);
String str;

void setup(){
  matrix.begin();
  matrix.setBrightness(1);

  Serial.begin(9600);
  Serial.setTimeout(30000);
  Serial.println(F("Connecting to WIFI!"));
  WiFi.mode(WIFI_STA);
  WiFi.begin("", "");

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

  Serial.println(F("\n\rWiFi connected!"));

  delay(2000);
}

String getData() {
  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient https;

  if (https.begin(*client, "https://api.krystofprasil.cz/")) {  // HTTPS
    Serial.println("[HTTPS] GET...");
    int httpCode = https.GET();

    // httpCode will be negative on error
    if (httpCode > 0) {
      // HTTP header has been send and Server response header has been handled
      Serial.printf("[HTTPS] GET... code: %d\n", httpCode);
      // file found at server?
      if (httpCode == HTTP_CODE_OK) {
        yield();
        String payload = https.getString();

        Serial.println(payload);

        return payload;
      }
    } else {
      Serial.printf("[HTTPS] GET... failed, error: %s\n\r", https.errorToString(httpCode).c_str());
    }

    https.end();
  } else {
    Serial.printf("[HTTPS] Unable to connect\n\r");
  }
}

void loop()
{

      const auto deser_err = deserializeJson(response, getData());
      if (deser_err) {
          Serial.print(F("Failed to deserialize, reason: \""));
          Serial.print(deser_err.c_str());
          Serial.println('"');
      } else  {
          Serial.print(F("Recevied valid json document with "));
          Serial.print(response.size());
          Serial.println(F(" elements."));
          yield();
          Serial.println(F("Pretty printed back at you:"));
          serializeJsonPretty(response, Serial);
          yield();
          Serial.println();
      }
      matrix.fillScreen(0);
      for (JsonObject elem : response.as<JsonArray>()) {
        yield();
        int x = elem["x"]; // 2, 2, 2
        int y = elem["y"]; // 2, 2, 2
        JsonArray rgb = elem["rgb"];

        int rgb_0 = rgb[0]; // 255, 255, 255
        int rgb_1 = rgb[1]; // 255, 255, 255
        int rgb_2 = rgb[2]; // 255, 255, 255

        matrix.drawPixel(x, y, matrix.Color(rgb_0, rgb_1, rgb_2));
        yield();
        Serial.println(y);

      }
      matrix.show();

  delay(10000);
}


texts:
im trying to make a speedometer with arduino Nano Board but when i use interrupt im getting "strange" number on variables t1 or t2 going under 0 there is the code:

volatile int impulsi =  0;
int impulsiOld = 0;
volatile int appoggio = 0;
//static int inizioDiNuovo = 0;
volatile unsigned int deltaT[3];
long t1=0;
long t2=0;

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

  pinMode(2, INPUT_PULLUP);
  attachInterrupt(0, definisciTempi, RISING);

}

void loop() {

  Serial.println(impulsi);
  if (impulsi == impulsiOld || impulsi > impulsiOld)
  {
    ;
  }
  //Serial.print("N IMPULSI: ");
  //Serial.println(impulsi);
  if (appoggio == 3) {
    appoggio = 0;
    Serial.print("DELTA T 0 : ");
    Serial.println(deltaT[0]);
    Serial.print("DELTA T 1 : ");
    Serial.println(deltaT[1]);
    Serial.print("DELTA T 2 : ");
    Serial.println(deltaT[2]);

    t1 = (deltaT[1] - deltaT[0]);
    if (t1 == 0) {
      t1 = 1;
    }
    t2 = (deltaT[2] - deltaT[1]);
    if (t2 == 0) {
      t2 = 1;
    }
    int t = t1 + t2;

    Serial.print("TEMPO T1 ");
    Serial.println(t1);
    Serial.print("TEMPO T2 ");
    Serial.println(t2);

  }

}

void definisciTempi() {
  impulsi++;
  switch(appoggio){

    case 2:
    //Serial.println("ASSEGNO DELTA T 2");
    deltaT[2] = millis();
    //Serial.println(deltaT[2]);
    appoggio = 3;
    break;

    case 1:
    //Serial.println("ASSEGNO DELTA T 1");
    deltaT[1] = millis();
    appoggio = 2;
    break;

    case 0:
    //Serial.println("ASSEGNO DELTA T 0");
    deltaT[0] = millis();
    appoggio = 1;
    break;

  }
}

how suggest i changed

unsigned int t1=0; unsigned int t2=0; into `long t1=0; long t2=0;`

output on Serial now have negative number it's for the interrupt??:

DELTA T 0 : 8785
DELTA T 1 : 8666
DELTA T 2 : 8706
TEMPO T1 40
TEMPO T2 -119  <------how 8706-8666= -119 ?

this is my pulse generator code:

const int pin = 2;
void setup() {
  pinMode(pin,OUTPUT);

}

void loop() {
 digitalWrite(pin,HIGH);
 delay(40);
 digitalWrite(pin,LOW);
 delay(40);
}


texts: I'm new to all of this, but it's there a way to group a cluster of pins to one variable? I don't necessarily want the grouped pounds to be sequential.


texts: Powering Arduino Uno and Ardumoto Motor Driver Shield

texts:
I need to power an Ardumoto Shield to drive two 12V DC motors. I was planning to connect a 12V battery to the Max 18V input on the Ardumoto and a 9V battery to the barrel jack input of the Arduino Uno.  Can you tell me if this should be ok or if it would cause any damage to the Arduino?

It mentions in the Ardumoto hookup guide:

There's no mention of the Max 18V input on the Ardumoto.. Advice appreciated, thanks.


texts: Dynamic Serial port selection and use without instantiating all Serialx objects

texts:
I have an arduino project that reads a config file from SD and then receives data on a serial port that is specifed in the config file.

I therefore need to instantiate the Serial (Serial0), Serial1,..2,3, etc based on dynamic data.

I am using a mega2560 with 4x HardwareSerial. Serial (also Serial0) is the USB. Serial 1, 2, 3 are on specific hardware pins.

I started with code something like:

uint8_t InitPort(uint8_t port) {
    switch (port) {
        case 0:
            if(Serial.begin(9600) return 1;
            break;
        case 1:
            if(Serial1.begin(9600) return 1;
            break;

        ... etc...

        default:
            return 0;
}

However, this instantiates all Serialx objects (using 157 bytes of data/bss each).

I've since written a class wrapper that takes a referece to the desired serial object as an initialising paramter, but this just pushes the problem up-stack to the calling code.

Is there a way that a Serial object can be instanitated dynamically with a port number passed in, to only end up with one instance connected to the desired port?


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

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

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

Thank you,
João


texts:
I have this time of flight laser distance sensor: http://www.dx.com/de/p/cjmcu-vl53l0x-tof-laser-distance-measuring-sensor-module-purple-449081#.WSbn52jyi70

The example code of the VL53L0X-arduino library is not working; I always get the serial message

  65535 TIMEOUT

However, I guess that the problem is at the sensor. The communication is via I2C, so that the i2c scanner should find it's address, right?

This finder doesnot find any address - am I right, that then the problem is at the sensor?

I connected VCC to (nearly) 5V, GND to GND, SCL to A5 and SDA to A4 (Arduino Uno)


texts:
I don't actually have to achieve this, it's more of an attempt to see what the best way to do this is. I'm sure the answer also differs depending on what circuitry you're trying to connect.

In this case, I plan on an Arduino (probably a Pro Mini or similar) that will control some RGB LEDs (via the WS2811 chip). If I wanted to add a second Arduino that would drive the LEDs if the first one failed (obviously very unlikely), I was wondering how I would do it. The WS2811 chip takes 5V, GND and data in.

My best attempt at a solution is using 3 relays which are SPDT. Connect the LEDs to the main Arduino via the normally open, which is controlled by that particular Arduino, and connect the LEDs to the backup Arduino via the normally closed, which is held open by the main Arduino. In the event of a failure, the main Arduino would lose connection to the LEDs while the backup would make a connection.

This probably isn't a very safe way of doing it (especially if the relay failed for example). Is there a way to do this?

The two Arduinos will be powered from two separate laptops.


texts: How to replace the delay() function in my code?

texts:
I'm new to Arduino and I currently have a project that involves the control of an LED via ultrasonic sensor. Basically, if an object passes through the ultrasonic sensor, the LED will be ON for 5 seconds but adding another set of LED and ultrasonic sensor with the same function gives a problem because the other LED won't light up if the other one is ON and vice versa because of the delay whereas what I want is to be able to make them both light up and stay lit for 5 seconds after their respective ultrasonic sensors detect an object. I've tried using the "Blink without delay" example but I can't understand it nor make it work. Please help me guys and thanks for reading. Here is my current code:

int trigPin1=2;
int echoPin1=3;

int trigPin2=4;
int echoPin2=5;

int led1=10;
int led2=11;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  pinMode(led1,OUTPUT);
  pinMode(led2,OUTPUT);
}

void loop() {
  long duration1, distance1;
  digitalWrite(trigPin1, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin1, HIGH);
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = (duration1/2) / 29.1;

   if (distance1 >= 500 || distance1 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print ( "Sensor1  ");
    Serial.print ( distance1);
    Serial.println("cm");
       }

  long duration2, distance2;
  digitalWrite(trigPin2, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin2, HIGH);
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin2, LOW);
  duration2 = pulseIn(echoPin2, HIGH);
  distance2= (duration2/2) / 29.1;

  if (distance2 >= 500 || distance2 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print("Sensor2  ");
    Serial.print(distance2);
    Serial.println("cm");
       }

  if(distance1>20 || distance2>20){
    digitalWrite(led1,LOW);
    digitalWrite(led2,LOW);
  }
  else if(distance1<20){
    digitalWrite(led1,HIGH);
    delay(5000);
  }

  else if(distance2<20){
    digitalWrite(led2,HIGH);
    delay(5000);
  }
}


texts: esp8266 garbage out only when using SoftwareSerial

texts:
I'm trying to operate the esp8266. When I connect RX+TX pins to pins 1+2 on the Arduino, everything works fine. but when I'm trying to use software serial all hell breaks loose and the recieved data is garbadeged (It seems like everything is ok but I can't read the output data...
more interesting, the output is not consistent!

example:

#include <SoftwareSerial.h>
SoftwareSerial esp8266(11, 10); // RX, TX
void setup() {
    // put your setup code here, to run once:
    esp8266.begin(19200);
    Serial.begin(115200 );
}

void loop() {
    esp8266.write("AT\r\n");
    String buffer;
    Serial.print("SENDING AT...");
    for(uint64_t time = millis();(time+1000) > millis();)
       for(;esp8266.available();buffer+=(char)esp8266.read());
    buffer.replace("\r\n"," ");
    Serial.println("RESPONSE:" + buffer);
}

And the output:

I've tried changing the SerialMonitor baud rate, the input pins, but results are all the same.

I've recently changed the MCU(uno) to a different and even a different esp module from a different supplier,
I am still getting the same results! I can't be the first one to encounter such phenomena...


texts: sending room temp data from multiple esp8266's to Mega 2560 to control CH gas boiler

texts:
My existing Arduino Mega set up has been in use for about 4 years controlling my gas CH system & heat pump HW system using an Arduino mega & 13 'wired' DS18B20 sensors; 2 of these sensors monitor the main room (lounge) temperature & 1 sensor monitors the outside temp. These 3 sensors control the CH by gas boiler using an algorithm that constantly adjusts the room temp setting as the outside temp changes. The others monitor HW tank temps, heat pump inlet & outlet temps.

I want to change this 'single zone' CH control to a 'multi zone' control using many more temp sensors (DS18B20 or ESP8266?) but laying in hidden wiring would be a real pain.

I've been looking at using ESP8266-07 as a wireless temp sensor for each 'zone', sending its data to the Mega for processing by the above refered to algorithm, so that the Mega can control the CH system better but I can't find any reference to receiving this wireless data at the Mega for processing within the IDE sketch.

I've tried testing the nRF24L01 & nRF24L01+ but my house has many 'black' reception areas & transmission is unreliable.
My 2.4GHz wireless LAN has 3 extenders around the house so this would be my prefered wireless solution.

Could a wireless 'master' be used at the Mega to process data coming in from the 'slave' sensors or am I misunderstanding this?

My programming skill is limited to 'basic IDE' & I find 'wireless' a bit of a black art (I'm a retired mechanical engineer!)


texts:
So my SIM900 GSM Shield is working fine with Netlight LED blinking and Status LED solid light, after I upload the code nothing happens about mySerial() in my serial monitor. Can I take your time for you to check this code out? I wonder if the problem lies here.

#include<SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

/*void SIM900power()
{
  pinMode(9, OUTPUT);
  digitalWrite(9,LOW);
  delay(1000);
  digitalWrite(9,HIGH);
  delay(2000);
  digitalWrite(9,LOW);
  delay(3000);
}*/
void setup() {
  // put your setup code here, to run once:
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);
  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();
  mySerial.println("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
  updateSerial();
  mySerial.println("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
  updateSerial();
  mySerial.println("AT+CREG?"); //Check whether it has registered in the network
  updateSerial();
  mySerial.println("AT+COPS?"); // Check that you're connected to the network;
  updateSerial();
}

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

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

Output:


texts: Notifications in constant loop (Blynk) trying to trigger along with serial function

texts:
This is an extension from a previous thread that was getting lengthy and off the original topic. I have the following code which monitors the state of a float switch (high or low). I upload the sketch, turn on the serial monitor and manually move the float switch up and down. The serial monitor output represents what I'm doing with the switch. The issue is that I get a constant loop of blynk notifications, every 15 seconds or so. Furthermore, if i move the switch to it's low position, the first blynk notification i get is correct reading "low", the following notifications are "high" thereafter. When the switch is moved to the high position, blynk just loops stating it's "high". I know it's weird and took quite a while to even establish what is going on here. but the biggest issue is the loop of notifications every 15 seconds.

#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
BlynkTimer timer;

char auth[] = "710a4af9b1d82412fa477705bf642c634";
char ssid[] = "ssid";
char pass[] = "pwd";
int flag=0;
int floatSavedState = -1;      // initial float low state indicates not yet known

void notifyOnButtonPress()
{
  // pin D1 will be 1 if float has dropped due to low water level
  // pin D1 will be 0 if water level is high enough
  int floatLevelLow = digitalRead(D1);  // read the float low indicator pin

  if (floatLevelLow && floatLevelLow != floatSavedState) {
       // send notification if this is first time or if the float level has
       // changed since the last notification.
       Serial.println("Resevoir Water is Low!");
       Blynk.notify("Alert : Water Level low.");
       floatSavedState = floatLevelLow;
  } else if (floatLevelLow != floatSavedState)
     // send notification if this is first time or if the float level has
     // changed since the last notification.
     Serial.println("Resevoir Water is High!");
     Blynk.notify("Alert : Water level high");
     floatSavedState = floatLevelLow;

}
void setup()
{
  // Debug console
  Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
  // Setup notification button on pin D1
  pinMode(D1,INPUT_PULLUP);
 timer.setInterval(16000L,notifyOnButtonPress);

}
void loop()
{
  Blynk.run();
  timer.run(); // Initiates BlynkTimer
}


texts: Determing approximate bicycle speed for distancemeter

texts: I'd like to build a self-contained bicycle distancemeter similar to those now used by local police, i.e. that measure and display the distance between the bicycle handlebar's end and passing cars and beep when distance is less than 1m on 50-km/h roads. In order to avoid detecting cars when stopped at traffic lights, I need to determine whether the bicycle is moving above a minimum speed, say 10 km/h. How can I do that without having to install additional hardware on the bicyle, like a magnet on the wheel and a sensor on the fork? Accelerometers?


texts: ESP8266, prints ready at start but no response to AT command

texts:
I have been using ESP8266 wifi module with Arduino as FTDI. The power for ESP8266 comes from LM317 5V - 3.3v regulated supply(I am sure 5V is powerful enough to give upto 1A of current).

The RX of ESP8266 is connected to RX of Arduino via a voltage divider to ensure 3.3V logic level. But still, I am not getting any response to AT command, though my laptop and phone wifi have successfully connected to AI-Thinker... SSID(which is an open hotspot from ESP8266).

I am also having some garbage values on the serial port immediately after I turn on the power supply to ESP8266. I have tested all baud rates available in Arduino IDE v1.0.5 with no results.

The resistor values for lm317 are R1 = 125 Ohm, R2 = 225 Ohm with which I am getting around 3.2 Volts.

The connections are as follows:-

-----Arduino UNO-----

RESET ------------ GND

Arduino UNO ----- ESP8266

TX ------------------- TX

RX ---5V to 3.3v--- RX

GND ----------------- GND

ESP8266 --------- LM317(5V to 3.3V)

VCC --------------- 3.3V

GND --------------- GND

CH_PD ------------ 3.3V

EDIT - 1: I have bought a new ESP8266, and even it doesn't responds to any AT commands, thought there is some difference in the previous ESP8266 output and this new ESP8266 output.

The difference is a sort of good news to me, it sends ready after sending some garbage at 115200 baud on boot which never happened with previous one(ESP8266).

Is anyone having some clue why there is no response to AT commands?
May it be a issue with TX line?

EDIT - 2: I have also used another Arduino with same connections doubting the TX pin on Arduino, but with same luck, bad luck. Still, nothing got changed.

EDIT - 3: I am shifting 5v to 3.3v by using three 100 ohm resistors.


texts: No Information obtained when using 2 x SoftwareSerial ports on Arduino Nano

texts:
I have a LoRa Click Module and Adafruit Ultimate GPS which both use Serial Communication.

I wish to just check the initial tests with all the components in on the Serial Console. Hence I have declared :

SoftwareSerial GPSSerial(10,11);
SoftwareSerial LoRaSerial(5,6);

Apparently when I declare them and upload the code on the board I do not obtain any information.

observations

However when I comment out the LoRaSerial declaration I obtain the GPS coordinates.
When I set the SoftwareSerial LoRaSerial(10,11) I retrieve the information.
I thought 5,6 pins won't be the right choice and hence went on the set SoftwareSerial(8,9) but I retreive no information.

inference

Nano cannot take into consideration more than 1 SoftwareSerial Component. However the Official Documentation states that all Digital pins can be used for Software Serial.

Is it too much for a Nano to have overall 3 Serial ports (including Serial itself)?

sketch

#include <SoftwareSerial.h>
#include <TheThingsNetwork.h>

SoftwareSerial GPSSerial(10, 11); //RX , TX
SoftwareSerial LoRaSerial(8,9); // RX, TX (tried with 5,6 too)
#define freqPlan TTN_FP_EU868

 TheThingsNetwork ttn(LoRaSerial, Serial, freqPlan);
void setup() {
  Serial.begin(115200);
  GPSSerial.begin(9600);
  LoRaSerial.begin(57600);
}
void loop() {
  delay(2000);
  while (GPSSerial.available()) {
    char c = GPSSerial.read();
    Serial.write(c);
  }
  delay(2000);
  while (LoRaSerial.available()) {
    ttn.showStatus();
  }
  delay(2000);
}


texts: Sending .txt / file transfer from SD card from arduino to server using rest api and MongoDB

texts:
I am currently working on a project where I have to read data from sensors and save it on a local MongoDB database using REST API. I am considering an edge case where wifi is not available I have to save it on SD card. How can I upload this saved data on REST API or using any other methods when wifi is again available?
I am new to Arduino and web development


texts: Code working well on Arduino Uno is not working with Mega 2560

texts:
Following is the code block from my script. It uses timer1. Why it is not compatible with Arduino Mega?

TCCR1A = theTCCR1A; // 0b10000010;
  /*10 clear on match, set at BOTTOM for compA.
   00 compB disconected initially, toggled later to clear on match, set at BOTTOM.
   00
   10 WGM1 1:0 for waveform 15.
   */
  TCCR1B = 0b00011001;
  /*000
   11 WGM1 3:2 for waveform 15.
   001 no prescale on the counter.
   */
  TIMSK1 = 0b00000001;
  /*0000000
   1 TOV1 Flag interrupt enable.
   */
  sei();             // Enable global interrupts.
  // Set outputs pins.
  DDRB   = 0b00000110; // Set PB1 and PB2 as outputs.
  pinMode(13, OUTPUT); // Set trigger pin to output


texts:
I am using nRF24L01 to communicate between two micro controllers. Both are Arduino Uno.

The question i have here is , even if i do not send any data from sender to receiver , the receiver device is constantly checking for the data, and the blank data is being received per second. And also no data is received by receiver which is sent by sender.

I am sharing the code for both sender and receiver.

Please suggest me what wrong i am doing.

Receiver Code :

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CNS, CE
String response;
boolean done = false;

void setup() {

 delay(500);
 Serial.begin(9600);

 radio.begin();
 radio.setPALevel(RF24_PA_MIN);
 radio.openReadingPipe(0, 0xF0F0F0F0AA);
 radio.startListening();

}

void loop() {

   if (radio.available()) {

   radio.read(&response, sizeof(response));
   done = true;

}

if (done) {
  Serial.println(response);
}

done = false;
delay(1000);

}

Sender Code:

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CNS, CE
String request;

void setup() {

delay(500);
Serial.begin(9600);

radio.begin();
radio.openWritingPipe(0xF0F0F0F0AA);
radio.setPALevel(RF24_PA_MIN);
radio.stopListening();

}

void loop() {

   while ( Serial.available() > 0 )  {

   request = Serial.readString();

   Serial.println(request);
   radio.write(&request, sizeof(request));

   delay(1000);

 }
}


texts:
I'm measuring capacitance of a system using a multimeter, and found that the value is very small (fluctuate from 50pF to 100 pF). The system is dynamic so the capacitance changes over time.

Now I need to log this value to some text file (csv for example). How could I do this with Arduino? If it's resistance, I could have built a simple voltage divider and sense the voltage using ADC. Also C is very small, I haven't been able to construct some measuring circuit for C.


texts: Mega  esp8266 comms sending baffling data

texts:
I have Wemos Mega-ESP8266 board. I have uploaded a simple WebSocket server on the ESP...

#include <ESP8266WiFi.h>
#include <WebSocketsServer.h>

const char* ssid     = "SKYNET";
const char* password = "yourdogsfavouriteauntysmaidenname";

WebSocketsServer webSocket = WebSocketsServer(81);

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) {

    //Serial.printf("[%u] get Message: %s\r\n", num, payload);

    switch(type) {
        case WStype_DISCONNECTED:
            break;

        case WStype_CONNECTED:
            {
              IPAddress ip = webSocket.remoteIP(num);
              Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload);
            }
            break;

        case WStype_TEXT:
            {
              String _payload = String((char *) &payload[0]);
              Serial.print(_payload);
            }
            break;

        case WStype_BIN:
            {
              hexdump(payload, lenght);
            }
            // echo data back to browser
            webSocket.sendBIN(num, payload, lenght);
            break;

    }
}

void setup() {

  // Set up serial comms
  Serial.begin(115200);

  // Set up WiFi
  WiFi.begin(ssid, password);
  while(WiFi.status() != WL_CONNECTED) {
     Serial.print(".");
     delay(200);
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  delay(500);

  // Set up web socket
  Serial.println("Start Websocket Server");
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}

void loop() {
  webSocket.loop();
}

I upload via the Arduino IDE & everything looks fine except the ESP doesnt send any information back through the serial monitor (yes I have the DIP switches correct for serial <> ESP comms).

I tried to see if was sending anything through the Mega via Serial3, the mega code (DIP switches set accordingly & ESP serial switch set to RX3). Mega code...

// Input buffer from ESP8266
String temp;

void setup() {
  // Set up serial comms
  Serial.begin(115200);   // Debug to Serial Monitor
  Serial3.begin(115200);  // From ESP8266
}

void loop() {
  while (Serial3.available()) {
      Serial.println(".......");
      Serial.println("In from ESP8266");
      temp = Serial3.readString();
      Serial.println(temp);
      Serial.println(".......");
  }
}

So now I get 2 one time messages to the serial monitor..

.......
In from ESP8266
[WS-Server] Server Started.

.......
.......
In from ESP8266
pm open,type:2 0

.......

I have no idea where these messages are being generated or why the ESP isnt sending the serial messages on set up eg the IP address for the ESP etc.

Any idea what's going on here?

Edit 1: Addition info asked for in comments (or at leat I think this is what was asked for)

Edit 2:

DIP switch settings for flashing the ESP - OFF, OFF, OFF, OFF, ON, ON, ON

DIP switch settings ESP > serial monitor - OFF, OFF, OFF, OFF, ON, ON, OFF (RX switch to TX0)

DIP switch settings for ESP > Mega > serial monitor - ON, ON, ON, ON, OFF, OFF, OFF (RX switch to TX3)

Edit 3 I have to press the red reset button after flashing the ESP8266 & it works BUT as soon as I unplug & restart nothing again! The client connects, sends the same data but it doesnt get echoed back via the serial comms. The only way to get to work again is to reflash the ESP8266 and hit the reset button.

Edit 4 Swapped out the board & now nothing works again. Uploads look fine but no serial comms at all from the ESP8266.


texts:
I want to control these motors: hexTronik DT750 Brushless Outrunner 750kv with this battery: Turnigy 2200mAh 3S 25C Lipo Pack and these ESCs: TURNIGY Plush 18amp Speed Controller.

I am new to this field of driving brush-less motors. Can someone tell me if I need anything else? Will this set-up work without anything getting destroyed?


texts: Why is there a need of use delay() after using Serial.flush() in the program

texts:
This code is a part of a long code for understanding serial communication and the functions related to it.
char buffer[18];
int red, green, blue;
int RedPin = 11;
int GreenPin = 10;
int BluePin = 9;

void setup()
{
Serial.begin(9600);
Serial.flush();
pinMode(RedPin, OUTPUT);
pinMode(GreenPin, OUTPUT);
pinMode(BluePin, OUTPUT);
}

void loop()
{
if (Serial.available() > 0) {
int index=0;
delay(100); // let the buffer fill up
int numChar = Serial.available();
if (numChar>15) {
numChar=15;
}
while (numChar--) {
buffer[index++] = Serial.read();
}
splitString(buffer);
}
}

In void setup(), Serial.flush() is used. On internet, I have read that it flush out any character present in a serial line. After calling it we can be sure that all the data has been sent before moving on to the next line of the program.
In void loop(), in the first if condition, delay(100) ensures to fill the buffer. Basically, buffer is the place in memory where the received serial data is stored prior to processing.
The question is that is there any need of using delay(100), if we call the Serial.flush() initially because it ensures that all the serial data has been transmitted (as in serial transmission one bit is transmitted at a time)? Does it takes further time to store the transmitted data in the memory (buffer) and does this is the reason to use delay(100)? Please clarify why delay(100) is used after calling Serial.flush(), I am confused.