texts: Servo Driven Through Custom Library Not working Properly

texts:
I'm a little new to Arduino, but not to programming or electronics in general.  I'm working on a library that will be more fleshed out later, but I'm having issues getting the basics working properly.

The following code produces the desired behavior if a servo is attached to pin 3:

#include <Servo.h>

Servo myServo;

void setup() {
  myServo.attach(3);
}

void loop() {
  myServo.write(1);
  delay(1000);
  myServo.write(45);
  delay(1000);
  myServo.write(90);
  delay(1000);
  myServo.write(135);
  delay(1000);
  myServo.write(180);
  delay(1000);
}

However, when I try to implement similar functionality in my own library the servo locks and just sort of grinds.  Here's the header file:

#ifndef MotorControl_h
#define MotorControl_h

#include "Arduino.h"
#include "Servo.h"

class MotorControl
{
  public:
    MotorControl(int north, int south, int west, int east);
    void setNorth(int value);
    void setSouth(int value);
    void setWest(int value);
    void setEast(int value);
    int getNorth();
    int getSouth();
    int getWest();
    int getEast();
  private:
    Servo _north;
    Servo _south;
    Servo _west;
    Servo _east;
    int _northVal;
    int _southVal;
    int _westVal;
    int _eastVal;
};

#endif

And here's the .cpp file:

#include "Arduino.h"
#include "MotorControl.h"
#include "Servo.h"

MotorControl::MotorControl(int north, int south, int west, int east)
{
  _north.attach(north);
  _south.attach(south);
  _west.attach(west);
  _east.attach(east);
  _northVal = 0;
  _southVal = 0;
  _westVal = 0;
  _eastVal = 0;
}

void MotorControl::setNorth(int value)
{
  _north.write(value);
  _northVal = value;
}

void MotorControl::setSouth(int value)
{
  _south.write(value);
  _southVal = value;
}

void MotorControl::setWest(int value)
{
  _west.write(value);
  _westVal = value;
}

void MotorControl::setEast(int value)
{
  _east.write(value);
  _eastVal = value;
}

int MotorControl::getNorth()
{
   return _northVal;
}

int MotorControl::getSouth()
{
  return _southVal;
}

int MotorControl::getWest()
{
  return _westVal;
}

int MotorControl::getEast()
{
  return _eastVal;
}

And finally, the code using the above library which should produce the same behavior as the code up top, but does not:

#include <MotorControl.h>

MotorControl mc(3, 5, 6, 9);

void setup() {}

void loop() {
  mc.setNorth(1);
  delay(1000);
  mc.setNorth(45);
  delay(1000);
  mc.setNorth(90);
  delay(1000);
  mc.setNorth(135);
  delay(1000);
  mc.setNorth(180);
  delay(1000);
}

I'm not sure what else to add ... this is running on an Uno R3.

Edit:  This is interesting.  I've tried the code from this example:
How do I initialize a servo object in my own library?
which works out just fine.  I'm still not sure that I see what I'm doing incorrectly here.  I see the differences between my code and the example, but not how they are causing problems.

If it's worth mentioning, I've also stored my library in the libraries folder.  Just throwing out any random detail I can think of.


texts: Unable to interface AD7705 (SPI) with Arduino

texts:
Code as shown below. I am unable to get the 16-bit data. Can someone help me identify my mistake?

byte spiTransfer(volatile byte data) {
  SPDR = data;
  while (!(SPSR & _BV(SPIF)));
  return SPDR;
}
#define DOUT      (50)
#define DIN       (51)
#define SCLK      (52)
#define CS_AD7705 (53)
#define DRDY (4)

void setup() {
  Serial.begin(9600);
  pinMode(DOUT, OUTPUT);
  pinM ode(DIN, INPUT);
  pinMode(SCLK,OUTPUT);
  pinMode(CS_AD7705,OUTPUT);
  pinMode(DRDY,INPUT);
  SPCR = _BV(SPE) | _BV(MSTR) | _BV(CPOL) | _BV(CPHA) | _BV(SPI2X) | _BV(SPR1) | _BV(SPR0);
  delay(10);
  digitalWrite(CS_AD7705, LOW);
  spiTransfer(00010000); //setup register
  spiTransfer(01100110);
  spiTransfer(00100000); //clock register
  spiTransfer(00001000);
  digitalWrite(CS_AD7705, HIGH);
}

void loop() {
  unsigned int data=0;
  digitalWrite(CS_AD7705,LOW); // enable device
  while(!digitalRead(DRDY));
  data = spiTransfer(00111000);  // select ch1 and setup read 16-bit data register
  data = spiTransfer(0)<<8;
  // Get the most significant 8 bits
  Serial.println("data : "+data);
  data |= spiTransfer(0); // Get the least significant 8 bits
  digitalWrite(CS_AD7705, HIGH); // release device
  delay(1000);
  Serial.println(data, HEX);
}


texts: Why can't I upload GRBL but I can upload other sketches

texts:
I had GRBL running on an Arduino UNO (China Copy).

When I tried to update to the newest GRBL Version I was not able to upload the sketch:

  avrdude: stk500_recv(): programmer is not responding)

I was unable to reprogram a bootloader via another ARDUINO (Arduino ISP) but I was able to update the firmware (dfu-programmer)

The funny thing is that I was only able to program the DFU as AT90USB82 not as ATmega8U2 while the chip has an ATmega8U2 printing.

I can upload any example sketch from Arduino IDE but not GRBL.

Any suggestions?


texts: Running light, without delay, and a potentiometer

texts:
I am just getting hands on to my Arduino Uno.

I am have finished the blinking light tutorial, managed to read a potentiometer, build a running light with delays and as well a binary counter.

Now I build a small project with 5 LEDs and a potentiometer to configure a running light and change the speed of the running light with the potentiometer.

The LEDs are connected to the pins 13 to 9 and the potentiometer is connected A0 and 5V.

I also managed to program it without a delay function, but I think it is rather ugly.

Is there a better way of doing this like I did it?

int led1 = 13;
int led2 = 12;
int led3 = 11;
int led4 = 10;
int led5 = 9;
//the delay
int pause = 1500;
//count to decide which LEDs are HIGH and which are LOW
int count = 0;
// will store last time LED was updated
unsigned long previousMillis = 0;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);

  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {

  unsigned long currentMillis = millis();

  // read the input on analog pin 0:
  pause = analogRead(A0);
  float voltage = pause * (5.0 / 1023.0);

  // print out the value and teh corresponding voltage you read:
  //Serial.println("Value: %d and Voltage: %f", pause, voltage);
  Serial.print("Value: ");
  Serial.println(pause);
  Serial.print("Volts: ");
  Serial.println(voltage);

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

    if (count == 0) {
      digitalWrite(led1, HIGH);
      digitalWrite(led2, LOW);
      digitalWrite(led3, LOW);
      digitalWrite(led4, LOW);
      digitalWrite(led5, LOW);
    }
    else if (count == 1){
      digitalWrite(led2, HIGH);
    }
    else if (count == 2) {
      digitalWrite(led1, LOW);
      digitalWrite(led3, HIGH);
    }
    else if (count == 3) {
      digitalWrite(led2, LOW);
      digitalWrite(led4, HIGH);
    }
    else if (count == 4) {
      digitalWrite(led3, LOW);
      digitalWrite(led5, HIGH);
    }
    else if (count == 5) {
      digitalWrite(led4, LOW);
    }
    else if (count == 6) {
      digitalWrite(led4, HIGH);
    }
    else if (count == 7) {
      digitalWrite(led5, LOW);
      digitalWrite(led3, HIGH);
    }
    else if (count == 8) {
      digitalWrite(led4, LOW);
      digitalWrite(led2, HIGH);
    }
    else if (count == 9) {
      digitalWrite(led3, LOW);
      digitalWrite(led1, HIGH);
    }
    else if (count == 10) {
      digitalWrite(led2, LOW);
      digitalWrite(led1, HIGH);
      count = -1;
    }
    count++;
  }
}


texts:
Changed ESP8266-01 to wrong settings by mistake. It was working ok
at 115200 (its default settings). It was connected like this:

PC->(USB)->Arduino->ESP8266.

Using Arduino as bridge

Pins 0 and 1 (RX/TX) connected directly to ESP8266 since I didnt have
USB to TTL adapter.
MCU removed so I could make that scenario work

It was just for testing AT commands. I did it like that because I realized that I was getting errors all the time trying to connect
using SerialSoftware (and different pins in Arduino).

Found out later that SerialSoftware does not work correctly at 115200...

So I issued the following AT command:

         AT+UART_DEF=9600,8,1,0,3

Now I cannot connect to the ESP8266 to correct that setting. All I get is garbage characters. I understand it's because of the flow control settings. I set it to both RTS and CTS which I also read later ESP8266 does not support?

Have tried:

Using Putty to change settings of COM port at connect. Have tried all speeps and flow control settings combinations I could think of. I get nothing or garbage characters.
Changing COM port setting from Device Manager (Windows 7)
Flashing ESP8266 using official tool (ESPFlashDownloadTool_v3.6.1.0).It won't sync with the ESP8266. It does not allow me to adjust speed to 9600. Minimun speed that show is 115200
Changing settings in ESPFlashDownloadTool_v3.6.1.0 so it will sync at 9600 (file: spi_download.conf)

I cannot think of anymore ideas. Have I completely messed up my ESP8266?

Is there a way that I'm not aware of that could fix this problem? How?

Thanks in advance!

Jorge


texts: Powering Arduino from 7805 voltage regulator

texts:
I am trying to build an Arduino Uno based robot. My questions are the following:

1) The motor driver also has an on-board 78M05 voltage regulator from ST electronics. I used a 9V battery to power the robot, and the 9V was connected to the input of the voltage regulator, and the +5V output I used to power the Arduino. I did so by connecting the 5V from the regulator to the 5V pin on the Arduino and the GND's together. I read that this is not advised, and solutions ranged from making sure the 5V is regulated, to connecting a diode between +5V and Vin to using one of the ICSP pins and so on. So which is actually a good way to do this?

2) I later realized that the DC motors are rated for max 6V dc, and so switched the 9V battery to 4x AA batteries giving a total voltage of 6V. When I connected this to the regulator, the regulator and the Arduino still turned on, even though the data sheet says the minimum input voltage is 7V. So what is going on here? Can anyone help me understand what is happening?


texts:
I'm new to the world of Arduino and I'm working on a wireless charging project that needs a 5.7MHz sine wave. I've tried using a Due and changing the PWM and DAC, but I can't get a clean sine wave at that frequency using anything I've found online. My signal is either way too low, or too high and horribly distorted.

Any help would be appreciated. I have access to a Mega, Due, Uno, and Mini.


texts:
I have design a circuit with 2 led (red and UV) and 2 button.So, the circuit supposed to work like this:
If i press the button for red led, the red led lights up and the uv led turn off, and if i press the button for uv led the uv led lights up and the red led turn off.

But the circuit is not work like that, when i upload the code, the uv led suddenly turn on without touching the button.The red led had no issue.The red led turn on when the button is push.And turn off when the button is unpress.But when i push the red button, the uv led does not turn off.It stay glow.The uv led turn on whatever i push the button or not.

Here is the code :

int red = 8;
int uv = 9;
int redbutton = 2;
int uvbutton = 3;
int redbutcondition = 0;
int uvbutcondition = 0;

void setup()
{
  pinMode (red, OUTPUT);
  pinMode (uv, OUTPUT);
  pinMode (redbutton, INPUT);
  pinMode (uvbutton, INPUT);
}

void loop()
{
  redbutcondition = digitalRead(redbutton);
  uvbutcondition = digitalRead(uvbutton);

  if (redbutcondition == HIGH)
  {
    digitalWrite(red, HIGH);
    digitalWrite(uv, LOW);
  }
  else if(uvbutcondition == HIGH);
  {
    digitalWrite(uv, HIGH);
    digitalWrite(red, LOW);
  }
}


texts: Difference between data type int and long on Arduino

texts:
I was learning to program for a void obstacle robot but when I looked at the code I saw two data types long and int.

Int are datatypes that holds  -2,147,483,648 to 2,147,483,647.
Long are also datatypes that holds -2,147,483,648 to 2,147,483,647.

Int and long are like same but I came up with the code where two types of datatype is used as seen below:

int trigPin = 2;
int echoPin = 4;
long duration, cm, inches;

But how can you know when to use which datatype? I searched a lot in the web but I didn't understand so can someone explain this to me please.


texts: message received from GSM contains parenthesis instead of curly braces

texts: the GSM code i have been working out is up and running, I use JSON format in sending the data obtained by my sensors, but the JSON message I have been receiving contains parenthesis instead of curly braces.


texts: I want to measure if my microwave has a leakage using Arduino. Ideally, I would like to get the exact number measured by mW/cm2 (similar to HT-M2 devices). Any advice which Arduino module can do it?


texts:
Well I am trying to save phone number as a string. For ease of use I want to add "+" character programmatically. Like this:
String cepNo ="+" + "901234567";

But program gives this error.
exit status 1
invalid operands of types 'const char [2]' and 'const char [13]' to binary 'operator+'

How to add "+" beginning of the string.


texts: Arduino Uno R3 ISR does not work on pin 2?

texts:
I have an Arduino Uno R3. I have a paddlewheel waterspeed sensor that I use on an ISR on pin 2. The power supply is approximately 8v stepped down to 4.92v with a circuit yanked from the phone charger. I have also tried this with the arduino 5v.

The pin returns the correct values with digitalRead(), so it's cycling between 1 and 0.

The ISR works fine on pin3. Why does it work on pin 3 and not pin 2 ISR?

void itest() {
    Serial.println( "test" );
}

void setup() {
    attachInterrupt(0, itest, FALLING);
}


texts:
I am trying modify this setup for two push buttons https://www.arduino.cc/en/Tutorial/Button.

The code seems rather trivial

int yellowButtonPin = 2;
int blueButtonPin = 4;

int yellowButtonState = 0;
int blueButtonState = 0;

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

void loop(){
  yellowButtonState = digitalRead(yellowButtonPin);
  blueButtonState = digitalRead(blueButtonPin);
  if (yellowButtonState == HIGH && blueButtonState == HIGH){
    Serial.write(3);
  }
  else if (yellowButtonState == HIGH && blueButtonState == LOW){
    Serial.write(2);
  }
   else if (yellowButtonState == LOW && blueButtonState == HIGH){
    Serial.write(1);
  }
  else {
    Serial.write(0);
  }
}

My problem is that there are several ground pins on the Arduino, but only one 5V pin, so I can't just simple double the circuits. Connecting the two circuits to different grounds but the same 5V didn't work out, although it seemed to be a good idea. How should I do this properly? To be honest, I actually would want to have three buttons, but I guess going from two to three will be trivial after going from one to two.


texts: RF24 communication between Leonardo and Micro not responding

texts:
I have Arduino Leonardo and Micro. I can't manage them to communicate via nRF24L01. I made a receiver and sender sketch to test it and can't see any respond. I tested the same code on two arduino nano and they work fine.

I connected the pins correctly using the ICSP pins in Leonardo and corresponding pins (not ICSP) dedicated for SPI in Micro.

Please could someone tell me what am I missing in porting sketch from nano-nano to leonardo-micro?

Here are the sketches:

PS some additional channels are left to see what I expected from working sketch.

Receiver module:

//NRF24
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
RF24 radio(9, 10);
byte addresses[][6] = {"1Node", "2Node", "3Node", "4Node"};

int channel = 1;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  radio.begin();
  radio.setAutoAck(1);
  radio.setRetries(15, 15);
  radio.openReadingPipe(1, addresses[0]);
  radio.openReadingPipe(2, addresses[1]);
  radio.openReadingPipe(3, addresses[2]);
  radio.openReadingPipe(4, addresses[3]);
  radio.startListening();
}

void loop() {
  // put your main code here, to run repeatedly:
  while (radio.available()) {
    char theMessage[13];
     radio.read(&theMessage, 13);
     Serial.println(theMessage);
     if(theMessage == "testingsend"){
       //this is removed in nano
      digitalWrite(13,HIGH);
      delay(50);
      digitalWrite(13,LOW);
     }
  }
}

And the sender:

//NRF24
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
RF24 radio(9, 10);
byte addresses[][6] = {"1Node", "2Node", "3Node", "4Node"};

int channel = 1;

void setup() {
  // put your setup code here, to run once:
  radio.begin();
  radio.setAutoAck(1);
  radio.setRetries(15, 15);
  radio.openWritingPipe(addresses[channel]);
}

void loop() {
  // put your main code here, to run repeatedly:
  char theMessage[13] = "testingsend";
  radio.write(theMessage, sizeof(theMessage));
  memset(theMessage,0,sizeof(theMessage));
  delay(300);
}


texts: With the press of a button, I need to play an intro sound file, then one of 50 other sounds in order, each time a button is pressed

texts:
I need to play an intro file and one of 50 different files after it in order each time the switch is pressed, with a short delay between the intro and next file.

For example let's say the intro is called "intro.wav," and each of the 50 other sound files are just named 01.wav-50.wav.

The logic would be:

TRIGGER
PLAY intro.wav
250ms DELAY
PLAY 01.wav
END

TRIGGER
PLAY intro.wav
250ms DELAY
PLAY 02.wav
END

TRIGGER
PLAY intro.wav
250ms DELAY
PLAY 03.wav
END

and so on, until all 50 files are played, then start over.

The messages are going to be a curated group of words. I'm not sure what the intro will be yet, but it will just be something like:

intro.wav = "The word of the day is"

01.wav = "help"

02.wav = "climb"

03.wav = "think"

I'm looking for some guidance on where to start with this, if an Arduino product would be suitable, and if so, which one.  I've worked with the Adafruit Audio FX Sound Board before, and that can almost do what I need it to do, but not by itself. It looks like I'll need an Arduino of some kind to accomplish this, so I went ahead ordered an Uno.

I'm not married to the idea of having the intro and word files separate either. If I need to create all 50 files to contain the intro and the word, that would be fine, as long as each one is triggered sequentially.

In that scenario, 01.wav could be "The word of the day is ... help" and the button would basically be the "next track" command.  I don't really have a problem with doing that because I'm all about keeping things simple and I don't think I'd run out of space, but I think it would be less time consuming to just dump all the individual word files onto the card.

The important thing is that the track(s) would play once, then stop, and when the button is pressed again, the next one plays.


texts: How to get readings on serial monitor in every 10s?

texts:
I am doing my final year project and here I am attaching the code I am using. According to the code, I will get the sensor output in serial monitor. But I want to get reading once n 10ms. Since serial monitor can't work with that resolution, I need to save the reading in an array and then output the array in serial monitor or any other way. Please help me in modifying the code.

The code is as follows:

/*
   The circuit:
  * VCC connection of the sensor attached to +5V
  * GND connection of the sensor attached to ground
  * TRIG connection of the sensor attached to digital pin 2
  * ECHO connection of the sensor attached to digital pin 4
 */

const int trigPin = 2;
const int echoPin = 4;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop()
{
  long duration, cm;

  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);

  cm = microsecondsToCentimeters(duration);

  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

  delay(100);
}

long microsecondsToCentimeters(long microseconds)
{
  return microseconds / 29 / 2;
}


texts: Generating Externally Triggered Complimentary PWM with Arduino Due

texts:
I need a 2KHz complimentary PWM waves with adjustable duty and phase that is triggered by an external 4KHz source.
After reading the datasheet I think there might be 2 way to do this:

Use a TC unit in capture mode, and somehow generate an interrupt when the count reaches 2. Use another TC unit in waveform mode to output phase-correct PWM. Use yet another TC unit to implement dead-time and generate the complimentary PWM.

Use the PWM controller, which already have complimentary PWM with dead-time build-in, but I'm not sure if it accepts external trigger.

If either of them is possible, could you please provide and example code ?
Thanks in advance !


texts:
I use a LCD display to display a not known size of text ( changes over time ). I wish to display it at the center of LCD ( 2X16 ).

I declare:

  char t[16];
  char h[16];
  sprintf(t, "%.1f%cC %.0f%%", temperature,223, humidity);

Now, since I want to add additional data on a specific line and center it, I need to know it size. When using:

sizeof(t)/(sizeof(t[0])

I get 16 which is the size determined and not its actual size.

How can I get the exact number of chars used?


texts: Im new here. Anyone that could give a code or sample that would generate I wanted to use a frequency in range of 35k-43kHz. Please help me.


texts: Digital input pin voltage treshold (voltage to register 1 or 0)

texts:
I was thinking of using multiple analog light sensors (variable resistance by light), but basically I only need to know if there is "a lot of light" or "not a lot of light". And would like to use interrupts.

Since I'm using multiple analog inputs, I can't set the ADC module to interrupt on a specific voltage, for each of the (5?) sensors?
I'd like to do this withouth using a external comparator.

I've checked the ATMega328p datasheet (going to use Arduino Nano probably).

The fun thing, however, is that on 5V a high signal is >2.6V and a low signal is <2.2V

What does this mean for the grey area? Would my inputs be glitching randomly? Would they maintain high, until below 2.2V and maintain low until above 2.6V? Or can the switching point be any where between that (and is it different per chip or pin?

EDIT: I've checked, my voltage divider circuit has 0.6V for "nothing" and 3V for "interrupted", so it should work neverthless. Though, I'm still interested in how the grey threshold area behaves.


texts: How To Get Data From Arduino Uno Onto My Laptop Through The USB

texts:
I want to write a c++ program that does something with the data from one of the input analog pins as the program runs, but I want to know how to get the value from the arduino uno though the USB port (that I am also using to power the uno) and into my laptop for using. IS there any documentation I should read?

My laptop runs Ubuntu 18.04 if that matters.

EDIT: I am not talking about the Serial monitor by the way


texts: Problem with action that should happen in loop(continuously)

texts:
I’m using WeMos D1 R2 and latest Blynk library and app. I am also using Arduino IDE 1.6.13. I am trying to read a button from the app, which works fine, but i want to read it continuously. Through the Serial Monitor I can see that the board changes modes as it should. However, even if sensors read values when we get through the first “if” states, the values do not continue to show up in Serial Monitor. I believe that’s happening because it is not working as a loop. Also, the relays are not working(they start as open as they should, but their state never changes), as I believe program freezes at some point.

Here is the code:

//Start of program
#include <dht11.h>
#define BLYNK_PRINT Serial//
#include <ESP8266WiFi.h>
#include <Blynk.h>
#include <BlynkSimpleEsp8266.h>
#include <NewPing.h>
#include <SimpleTimer.h>

#define TRIGGER_PIN2 D4 // Arduino pin tied to trigger pin on the ultrasonic sensor 2.
#define ECHO_PIN2 D5     // Arduino pin tied to echo pin on the ultrasonic sensor 2.
#define MAX_DISTANCE2  23// Height of the Water Tank 2 (in centimeters).
#define DHT11_PIN D6

char auth[] = "****";
char ssid[] = "8888";
char pass[] = "psw";

int Relay1 = D1;
int Relay2 = D2;
int val2 = 0;
int tankwater1 = 0; //water in tank 1 in liters
int tankwater2 = 0; //water in tank 2 in liters
int fieldsize1 = 0; //size of field1 in m^2
int fieldsize2 = 0; //size of field2 in m^2
int sensor_pin = D7;
SimpleTimer timer;
//NewPing sonar1(TRIGGER_PIN1, ECHO_PIN1, MAX_DISTANCE1); // NewPing setup
of pins and maximum distance.
NewPing sonar2(TRIGGER_PIN2, ECHO_PIN2, MAX_DISTANCE2); // NewPing setup of
pins and maximum distance.

void setup()
{
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
  Blynk.begin(auth, ssid, pass);
  pinMode(Relay1, OUTPUT); //Setup Relay pin as output pin
  pinMode(Relay2, OUTPUT); //Setup Relay pin as output pin
  //pinMode(led_pin, OUTPUT);
  pinMode(sensor_pin, INPUT);
  digitalWrite(Relay1, LOW);
  digitalWrite(Relay2, LOW);
}

void loop()
{
  Blynk.run();
  timer.run();
}

BLYNK_READ(V8)
{
  Blynk.virtualWrite(8, 23 - val2); // virtualpin 8 distance
}

BLYNK_WRITE(V1) {
  int pinValue = param.asInt();

  if (pinValue == 0)
  {
    val2 = sonar2.convert_cm(sonar2.ping_median());
    Serial.println("Irrigation mode is active");
    Serial.println("Water level is at:");
    Serial.println(23 - val2);

    if (digitalRead(sensor_pin) == HIGH)
    {
      if (val2 <= 15) //Water level reaches the Top of the Tank2
      {
        digitalWrite(Relay2, HIGH); //Pump2 off
        delay(500);
      }
      else if (val2 > 15) // Water is empty on the Tank2
      {
        digitalWrite(Relay2, LOW); // Pump2 ON
        delay(500);
        //delay(86400000); one day delay. not suitable for experiment
      }
      else if (digitalRead(sensor_pin) == LOW)
      {
        digitalWrite(Relay1, LOW);
      }
    }
  }
  else {
    Serial.println("Fertilize mode is active. This does nothing now");
    //val3 = sonar2.convert_cm(sonar2.ping_median());
    //tankwater2 = (10-val3)*fieldsize2; //calculation of water in tank2
  }
}
//End of program


texts: Use callbacks in Arduino with pointers to functions (will functions persist in memory?)

texts:
As I been learning Arduino (micro controllers, c++, etc) I have learned that memory is very limited. I already understand how memory works when it comes to variables. But I do not understand how memory works when it comes to functions. Since I am a backed developer I try to stay away from interrupts and instead use callback functions. Another reason why I prefer to use callback functions is because I love the visual studio IDE. I create my core functionality of whatever project I am building on a c++ project targeted for Windows. Once my algorithms/logic works the way I want it I reference those libraries on Arduino.
Anyways I am using lambdas to pass functions to my helper libraries. That way I do not use the delay function to wait for a response and I am always listening for events. Basically my question is if it is correct to have code like this (function SendEvent):
/* MyRadioLibrary.h */
// I am not including all the code of `MyRadioLibrary` because that makes it hard to
// understand what I am asking. Instead I will try to use a lot of pseudo-code. Let me
// know if you want me to post the code as an edit.

class MyRadioLibrary
{

public:

    static void SendEvent(int typeOfEvent, void(*onEventCompleted)(bool x))
    {
        // I have an array of pointers to functions
        void(*onEventCompletedBuffer[10])(bool x);

        // I enqueue that event with a queue helper class

        // Send event ....

        // DO NOW WAIT FOR RESPONSE SINCE CALL BACK IS ALREADY SAVED
    }

    static void loop() {

         // listen for radio messages
         if(radio.available()){
                // get response
                // dequeue pointer to call back
                // execute call back
          }

    }
};

And my arduino sketch contains this code:
#include <MyRadioLibrary.h>

void setup()  {
    // setup pins etc..
}

void loop()
{

    if (isButton1Pressed())
    {
        MyRadioLibrary::SendEvent(1, [](bool didEventCompletedSuccessfully) {

            if (didEventCompletedSuccessfully)
            {
                // turn on green LED
            }
            else {

                // turn on red led
            }

        });
    }
    else if (isButton2Pressed())
    {
        MyRadioLibrary::SendEvent(2, [](bool didEventCompletedSuccessfully) {

             // call back function

        });
    }

    MyRadioLibrary::loop(); // listen for response events. When we get one fire call back.
}

Now the question
When I call the SendEvent function I am passing 2 things (1) an integer and (2) a pointer to a function that is the call back. The integer (1) is passed as value and that will be part of the stack of the SendEvent function. The pointer (2) will be stored on an array of pointers. But what about the lambda function? where will that be stored? Instead of using a lambda function should I declare those functions in global scope and pass the global function instead of a lambda? Will I run the risk of the pointer (2) pointing to a function that no longer exists if I use this way of coding?


texts: Is there any way for one Arduino board to communicate with multiple sensors?

texts: Say a home IoT application to monitor water levels in basement at 4 or 5 different places and transmit that data back to a single Arduino board to be then interfaced with a GUI to do home monitoring?


texts: I've looked around a ton so it's probably not available but does anyone know if there is a usable core for the ATMega16u2 (the chip the Uno and Due uses for USB to Serial). I have a project I was going to use the 32u4 for but they aren't really available for several months and the 16u2 has all the functionality that I would really need.


texts: Strange behaviour on splitting char array and converting the chunks to int

texts:
I have this function:

void changeColor(char control[16])
{
  char _red[3], _green[3], _blue[3], _brightness[3], _white[3];
  int red, green, blue, brightness, white, offset;

  offset = 1;
  for (int i = 0; i < 3; i++) {
    _red[i] = control[i + offset];
  }
  offset = 4;
  for (int i = 0; i < sizeof(green); i++) {
    _green[i] = control[i + offset];
  }
  // strncpy(_green,control+offset,3); // same result
  offset = 7;
  for (int i = 0; i < sizeof(_blue); i++) {
    _blue[i] = control[i + offset];
  }
  offset = 10;
  for (int i = 0; i < sizeof(_white); i++) {
    _white[i] = control[i + offset];
  }
  offset = 13;
  for (int i = 0; i < sizeof(_brightness); i++) {
    _brightness[i] = control[i + offset];
  }

  red = atoi(_red);
  green = atoi(_green);
  //sscanf(_green, "%d", &green); //same result
  blue = atoi(_blue);
  white = atoi(_white);
  brightness = atoi(_brightness);

  Serial.print(" control ");
  Serial.println(control);
  Serial.print(" _red ");
  Serial.println(_red);
  Serial.print(" _green ");
  Serial.println(_green);
  Serial.print(" _blue ");
  Serial.println(_blue);
  Serial.print(" _white ");
  Serial.println(_white);
  Serial.print(" _brightness ");
  Serial.println(_brightness);
  Serial.print(" red ");
  Serial.println(red);
  Serial.print(" green ");
  Serial.println(green);
  Serial.print(" blue ");
  Serial.println(blue);
  Serial.print(" white ");
  Serial.println(white);
  Serial.print(" brightness ");
  Serial.println(brightness);
  //... do something with ints
}

And by calling from the setup:

 char _control[16]={'6','2','5','5','0','0','0','0','0','0','0','0','0','0','5','0'};
 //6255000000000050

 void setup() {
   Serial.begin(9600);
   // ... do something
   while (!Serial) {
     ; // wait for serial port to connect. Needed for native USB
   }
  changeColor(_control);
}

I get from console this output:

   control 6255000000000050
   _red 255ÿ
   _green 000255ÿ
   _blue 000000255ÿ
   _white 000050000000255ÿ
   _brightness 050000000255ÿ
   red 255
   green 255
   blue 255
   white 29951
   brightness 29951

Basically, the char array are filled with more elements than the actual dimension (3), but I don't get error or warnings from the compiler

I also tried with strncpy, strcpy, strncat, and by using the pointer in the for loops

for(int i=0;i<sizeof(_green);i++){
  _green[i]=control+i*sizeof(char)+offset*sizeof(char);
} // also without the sizeof()

And I got the same result in the console (with nl&cr), any hints?

EDIT:

Added NULL char

  ...
  char _red[4], _green[4], _blue[4], _brightness[4], _white[4];
  int red, green, blue, brightness, white, offset;
  _red[4]='\0';
  _green[4]='\0';
  _blue[4]='\0';
  _white[4]='\0';
  _brightness[4]='\0';
  offset=1;
  for(int i=0;i<3;i++){
    _red[i]=control[i+ offset];
  }
  // same as above

Output:

control 6255000000000050
_red 255
_green 100255
_blue 000100255
_white 0000050
_brightness 050
red 255
green 100
blue 0
white 50
brightness 50


texts: Can we use serial.begin command anywhere in code?

texts: When to use this command? What difference it would create if I add this command in loop function, setup function and declaration section?


texts: Fade LED strip using proximity and map() function

texts:
I'm using a sonar sensor to detect proximity, and need to control the brightness of an LED strip in direct relationship to the distance detected. For example, as someone moves toward the sonar, the strip needs to dim.

I'm using map() to do it now crudely but it's way too abrupt and I'm not sure how best to achieve the effect I'm looking for. Ideally, as the person moves toward the light, it very smoothly fades out in relationship to the person's movement/pace.

Initial thoughts / questions:

-- Can I use a more refined number type to set the LED brightness other than int?
-- Do I need to do something more complex where I detect the delta in the person's movement and use the loop to fade the LED from one value to another? Seems complicated...

Any help / ideas on this would be much appreciated! Existing code is below if it helps.
Claudia

//variables needed to store values
long pulse, inches, cm;

//LED VARIABLES
int frontPin = 6;    // front strip connected to PWN pin 5
long interval = 8000; // interval at which to do something (milliseconds)
int val;

void setup() {
  //This opens up a serial connection to shoot the results back to the PC console
  pinMode(frontPin, OUTPUT);
  pinMode(pwPin, INPUT);
  Serial.begin(9600);
}

void loop() {
    //Used to read in the pulse that is being sent by the MaxSonar device.
  //Pulse Width representation with a scale factor of 147 uS per Inch.

  pulse = pulseIn(pwPin, HIGH);
  //147uS per inch
  inches = pulse/147;
  //change inches to centimetres
  cm = inches * 2.54;

  if (inches < 36){
    detect();
  }
}

void detect(){
  Serial.print(inches);
  Serial.print("in, ");
  Serial.println();

  val = inches;
  val = map(val, 6, 36, 0, 255);

  analogWrite(frontPin, val);
  Serial.print("mapped value is ");
  Serial.print(val);

  delay(500);

}


texts:
So I followed the guide on GitHub to run this demo which compiles and runs. It does warn of some deprecations and such in the firebase libraries :

  In member function 'const String& FirebaseArduino::error()'  warning:
  returning reference to temporary [-Wreturn-local-addr]
       return error_.message().c_str();

It is failing to update my firebase database and the firebase error message is not being displayed, seems to be because of the above error. But this does make it complicated to debug...

Can someone please help me get around this?

Appreciate any feedback or pro tips :)

UPDATE

So found an issue on GitHub that solved connecting to the database. Fingerprint update apparently... https://github.com/FirebaseExtended/firebase-arduino/issues/369 but still would like to solve the firebase library error so that everyone can get legible error messages back when using it.


texts: What is causing this 'narrowing conversion' warning?

texts:
Because I'm still figuring out 'Arduino C' I leave all warnings on.

Recently I got this one:

narrowing conversion of '(int)(((unsigned char)bx_0) | ((unsigned char)bx_1))' from 'int' to 'const byte... etc.

...referring to this line:

const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};

...pointing to the or symbol.

The code in question (much simplified to recreate this):

const int latch[2] = {2, 4};

const byte bx_0 = 1 << latch[0];
const byte bx_1 = 1 << latch[1];

const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};

(This happens whether I use byte, uint8_t, or unsigned char everywhere.)

Without the or operator, no warning. If bx_0 and bx_1 are simple bytes, not shifted into existence, no warning. If I do this:

const byte pinMask[3] = {bx_0, bx_1, (byte)(bx_0 | bx_1)};

...again, no warning.

However, I get no complaints about this:

const byte notMask = !(bx_1 | bx_0);

...so a further condition is that the problem or has to be in an initializer list. Yikes.

I don't get it. There's no way an or of two bytes can force widening, so where did the (int) cast come from? It apparently has something to do with the 1 << latch[0] code, but the result of that is still a byte, by definition.

I have a solution -- the (byte) cast -- but in the real code it's ugly and feels unnecessary. Everything is already just bytes.


texts: Servo doesn't move if I detach it AFER the write?

texts:
So this is a bit weird, and I don't understand anything.
Basically, I'm just playing with my servo. I wrote a small program, which can be found at this link: https://pastebin.pl/view/8e9c9573 (Note: It's three files, I left some comments there, and the idk function is just my last resort, trying to separate myself from loop, I really don't know :/ ).
So I run controller.Setup() in the setup function, and then in loop I just move it to 180 and detach it, then I run into an infinite loop. Note: I know it's not very good code, but that's not what concerns me right now.
The problem is, when I add the call to detach (line 22), the previous move doesn't run! I think I'm going crazy, cause as soon as I remove the line and recompile, it actually moves.
I tried to remove the lock(Controller::m_Attached), and it still doesn't work. Please let me know if I didn't notice something, but I really don't understand.
Notes:

I'm using arduino-cli, here's my not-very-perfect Makefile: https://pastebin.pl/view/daa852ff
I use the Servo library: https://www.arduino.cc/reference/en/libraries/servo/
I'm using an Arduino Uno

EDIT:
Someone told me to post the code in the question, so here I go:
//Main.ino
#include <Servo.h>
#include "Controller.h"

Controller controller(3);

void idk();

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

void loop() {
    idk();
    while(true);
}

void idk() {
    controller.Move(180);
    controller.Unlock();
}

// Controller.h
#pragma once
#include <Servo.h>

class Controller
{
public:
    Controller(int servoPin)
        : m_ServoPin(servoPin), m_Attached(false) {}

    void Setup();
    void Move(int angle);

    void Lock();
    void Unlock();

private:
    Servo m_Servo;
    bool m_Attached;
    const int m_ServoPin = 3;
};

// Controller.ino
#include "Controller.h"

void Controller::Setup()
{
    m_Servo.attach(m_ServoPin);
    m_Attached = true;
    Serial.print("[CONTROLLER] Attached Servo\n");
}

void Controller::Move(int angle)
{
    if (m_Attached)
        m_Servo.write(angle);
}

void Controller::Lock() {
    m_Servo.attach(m_ServoPin);
    m_Attached = true;
}

void Controller::Unlock() {
    m_Servo.detach();
    m_Attached = false;
}


texts: Sending code for error detection facing problem with error not able to compile code

texts:
MY PROJECT CODE:

#include ESP8266WiFi.h
#include LiquidCrystal.h
#include FirebaseArduino.h>
#include HX711.h>
#define FIREBASE_HOST "iot-based-smart-dustbin.firebaseio.com"
#define FIREBASE_AUTH "ljIbV03K07rLwoHRKSaAxWzJNCb3Lh6buc76dkvb"
#define WIFI_SSID "AndroidAP"
#define WIFI_PASSWORD "ashu1234"
char c; //ESP
String data   = "";  //ESP
#define DOUT  15
#define CLK  13
#define IR1 14
#define IR2 12
HX711 scale(DOUT, CLK); // Init of library
float calibration_factor = -96650; //-106600 worked for 3-40Kg max scale setup
const int rs = 16, en = 5, d4 = 4, d5 = 0, d6 = 2, d7 = 10;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup()
{
   Serial.begin(9600);
   pinMode(IR1,INPUT);
  pinMode(IR2, INPUT);
  pinMode(DOUT, INPUT);
  pinMode(CLK, OUTPUT);
  lcd.begin(16, 2);     // Print a message to the LCD.
  lcd.print("WELCOME");
  delay(2000);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
//  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED)
    {
  //    Serial.print(".");
      delay(500);
    }
//  Serial.println();
//  Serial.print("connected: ");
//  Serial.println(WiFi.localIP());
  scale.set_scale();
  scale.tare(); //Reset the scale to
}
void loop()
{
  scale.set_scale(calibration_factor); //Adjust to this calibration factor
  float a=scale.get_units();   // a Variable to take weight values at input
  lcd.clear();
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.setFloat("Weight", a);  //to set value in firebase // value on a sent to weight variable
  if (digitalRead(IR1)==HIGH)
  {
    Firebase.setFloat("IR1", HIGH);
    lcd.setCursor(0, 0);
    lcd.print("Location 1:High");
  }
   if (digitalRead(IR1)==LOW)
  {
    Firebase.setFloat("IR1", LOW);
    lcd.setCursor(0, 0);   //column, Row
    lcd.print("Location 1: Low");
  }
   if (digitalRead(IR2)==HIGH)
  {
    Firebase.setFloat("IR2", HIGH);
    lcd.setCursor(0, 1);
    lcd.print("Location 2:High");
  }
   if (digitalRead(IR2)==LOW)
  {
    Firebase.setFloat("IR2", LOW);
    lcd.setCursor(0, 1);
    lcd.print("Location 2: Low");
  }
  delay(2000);
  lcd.clear();
  if (a>=4)
  {
    lcd.setCursor(0, 0);
    lcd.print("Weight: High");
  }
   if (a<4)
  {
    lcd.setCursor(0, 0);
    lcd.print("Weight: Low");
  }
 delay(2000);
}
void send_msg_1()
{
  Serial.println("AT+CMGF=1");// for GSM module in TEXT mode
  delay(1000);
  Serial.println("AT+CMGS=\"+9921526975\"\r");// Phone number (change)
  delay(1000);
  Serial.println("Dustbin at Location 1 is full");// Message body (change as per requirement)
  delay(1000);
  Serial.println((char)26);// send message
  delay(1000);
}

ERRORS I am Getting while compiling as follows:

sketch_jul18a:34:22: error: no matching function for call to 'HX711::HX711(int, int)'
 HX711 scale(DOUT, CLK); // Init of library
                      ^
C:\Users\Admin\Desktop\Neha\sketch_jul18a\sketch_jul18a.ino:34:22: note: candidates are:
In file included from C:\Users\Admin\Desktop\Neha\sketch_jul18a\sketch_jul18a.ino:23:0:
C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:30:3: note: HX711::HX711()
   HX711();
   ^
C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:30:3: note:   candidate expects 0 arguments, 2 provided
C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:19:7: note: constexpr HX711::HX711(const HX711&)
 class HX711
       ^
C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:19:7: note:   candidate expects 1 argument, 2 provided
exit status 1
no matching function for call to 'HX711::HX711(int, int)'

Please help me to solve this problem. Too much struggling...


texts:
I know there are a lot of threads about this, but i cant find answer for my problem.

I have SIM800L Mini and arduino uno. I want to create basic SMS send application, but problem is with SIM800L. I can connect it with USB-UART and communicate with it via AT terminal. I can set baud rate, send sms etc. But when I connect it with arduino, it doesnt work. Im using LM350 for powering it (4V) and voltage divider with 4k7 and 10k resistor.

Thank you for your help

EDIT:
Here is code:

#include <SoftwareSerial.h>

String Arsp, Grsp;
SoftwareSerial gsm(10, 11); // RX, TX

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

   Serial.begin(9600);
   Serial.println("Testing GSM SIM800L");
   gsm.begin(9600);

}

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

   if(gsm.available())
   {
      Grsp = gsm.readString();
      Serial.println(Grsp);
   }

   if(Serial.available())
   {
      Arsp = Serial.readString();
      gsm.println(Arsp);
   }
}

Here is wiring

Codes for arduino

Schematics

SIM800L


texts: Arduino port not showing serial USB Mac OS El Capitan

texts:
I don't see serial USB as an option under ports when my Arduino is connected to my Mac. I have used this Arduino on the same computer before without any issues on Yosemite OS. However, I was trying to run a servo motor and I don't think I was getting enough power so I decided to use an external power supply. 12V 500mA DC and connected it while still keeping the USB connection. Since I already had the servo program loaded, the motor did work. Then I tried uploading the program again, that's when I realized that there was no serial connection. I am not sure if the problem is because of the power supply that I connected.

I tried the following approaches without success:

Upgraded the OS to El Capitan (which might have been a bad decision in hindsight).
Tried connecting the Arduino to another Mac with new Arduino IDE download, same issue.
Tried downloading the FTDI drivers as suggested by other folks.

I searched for a few hours for a solution online, but nothing so far has helped. Please provide suggestions.


texts: How safely write to SD or Eeprom on Arduino power off

texts: I want to constantly store data to sd. But how I make sure data is not corrupted on moment of power off? I think I could add small capacitor on 5V and check when voltage drops, so I would stop data write. Or is there better solution for safe data write?


texts: I had a question, I tried to control a servo with the arduino, to the servo I attached a stick and at the end of the stick a little weight. After runing my code my servo tried to move the stick, but maybe it had not enough torque to move it so after that I paused the code. Then I tried to control the servo again without weight and this time it didn´t moved. Is it broken? why? Is there a posible solution? Thanks


texts: What is the Arduino compiler's version of `__unused` for function parameters?

texts:
When I first started with the Arduino environment I noticed that it had File | Preferences | Compiler Warnings set to None, so I set it to All - and there were many, many warnings in the supplied libraries! So I quickly set it to None again - until later.

Well, "later" is now, and I started going through the warnings to fix the code to quiet the compiler.

Note that I don't want to disable any warnings - I want to placate the compiler at each spot so that it says to itself "No problem here!"

If the compiler complains of an unused variable, I comment out the variable;
If it complains of a signed/unsigned comparison, I change the type;
If it complains of an unused parameter in a function, I...

...hmmm. If this was C++, I'd simply comment out the parameter name, leaving the type naked:

void Fn(int /*param*/) {
} // Fn(param)

  Arduino reports:
    error: parameter name omitted

But that isn't legal in C. With some compilers you can use the __unused attribute:

void Fn(int __unused param) {
} // Fn(param)

  Arduino reports:
    error: expected ';', ',' or ')' before 'param'
    It's interpreting __unused as the actual parameter name

or if they're fussy:

void Fn(int __attribute__((unused)) param) {
} // Fn(param)

  Arduino reports:
    warning: unused parameter 'param' [-Wunused-parameter]
    That's not the correct __attribute__, obviously

So none of the above work in the Arduino environment. Suggestions?

I've been programming in C and C++ for over twenty years, and I know that the #1 thing you should always do is ask the compiler to tell you about everything it notices. You need a warning-free compile at all times! Otherwise, you spend hours or days trying to find a bug - only to discover that the compiler has been warning you about it all along...


texts:
I recently got my esp8266-01 and for interfacing with Arduino I completed all the steps need for right form pins to board allotting from esp8266 community after everything I still get error of "connection failed fatal error : timeout ", so anyone just help out for
 soln ?
I am interfacing with empty code of loops only to check it's response at connectivity at first .


texts:
I am trying to connect to my robot car with the HC-02 module. The problem is that the module is visible on my phone only while the arduino uno board is connected to my laptop. At this point I can pair my phone with the module, but I can't controll the car. When I disconnect the car from my laptop and turn it on, HC-02 is not visible anymore. It's blinking fast which means it should be available for connecting. I cant access the AT mode and I don't know what to do anymore. Has anyone had problems with this.
My phone is Android, I also tried with another one and still not working.

I also removed arduino uno from the car, I connected only the Bluetooth module. I can see HC-02 when Arduino is connected to the PC with the USB cable. But when I disconnect it from the PC and power it with the battery it disappears from available devices.


texts: How do I pass an Int Array into void for a foreach loop?

texts:
I know its probably an odd question...but I found a workaround for a foreach loop in C. I have a whole bunch of int arrays that I would like to be able to pass into a void, which has that foreach loop in it. This is my code right now:

int example[] = {1, 2, 3, 4, 5};

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

    #define foreach(item, array) \
        for(int keep = 1, \
            count = 0,\
            size = sizeof (array) / sizeof *(array); \
            keep && count != size; \
            keep = !keep, count++) \
        for(item = (array) + count; keep; keep = !keep)
    }
}

void Words (int w[]) {
    foreach(int *v, w) {
        Serial.println(*v);
        delay(500);
    }
}

void loop () {
    Words (example);
}

However when I run it, it only returns the first number of the array, I need all 5 of them. I know theres all sorts of additional things that could be it, like the * or & symbol but I really don't understand what they do. Any ideas as to how to get that to work?


texts:
I want to ask is there a possible code to prioritize a specific part of a code? So I'm doing this project where I want to utilize muscle sensor, servo, and a button on an app over Bluetooth. The problem is since all is running in void() loop, even though I am not using the muscle sensor I can't move the servo with the app, since it reads the muscle sensor first. So is there a possible code to make the muscle sensor stop for a period of time after the button is pressed on the app and the servo is moved?

Here is the code:

void loop()
 {
  if(Serial.available()>0)
   {
    char data = Serial.read();

      if (data == 'a')
       {
        myservo.write(15);
       }
  }

int value = analogRead(EMG_PIN);

 if(value > THRESHOLD)
  {
   myservo.write(15);
  }

  else{
       myservo.write(140);
      }

So the first code is a bluetooth code where the servo is controlled through a button on an app. The second one is a muscle sensor. As stated above the problem is it will always read the muscle sensor even though the button is pressed from the app.

#include <Servo.h>

 int increment = 0;

 Servo myservo;

 void setup() {

   myservo.attach(1);

 }

 void loop()
 {

   Serial.println(increment++);

   if (increment > 9);
    {

     if(Serial.available()>0)
      {
       char data = Serial.read();

       if (data == 'a')
       {
        myservo.write(15);
       }
 }

      else if (increment = 0);

      int value = analogRead(EMG_PIN);

      if(value > THRESHOLD)
       {
        myservo.write(15);
       }

     else{
       myservo.write(140);
      }
  }


texts:
I understand the HMAC with SHA256 example provides a set of keys:
(https://github.com/Cathedrow/Cryptosuite/blob/master/Sha/examples/hmacsha256test/hmacsha256test.pde)

#include "sha256.h"
uint8_t hmacKey1[]={
  0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,
0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b
};
uint8_t hmacKey2[]={
  0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,
0x0e,0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19
};
...

I did a bit research and have a sense that these keys are in hexadecimal form with 0x added as prefix. If I like to use my own key, like a string, abece123*, do I just convert the key string to hex?

I tried to use this site below to convert above hmacKey2 to see what the key may look like. But the result is not recognizable. Here's what I did: copy and past

0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,
0x0f,0x10,0x11,0x12,0x13,0x14, 0x15,0x16,0x17,0x18,0x19

to the site below to convert to string.
https://codebeautify.org/hex-string-converter

I am very new to this field. Please help me understand how these key works and and the steps needed to replace one of the preset hmac keys with my own key string (e.g. abece123*). Thanks.


texts: How to have compiler know whether Arduino or ESP8266?

texts:
I am doing some work for both Arduino Mini Pro and for a NodeMCU style ESP8266 board. Within the Arduino IDE I tell it what board I am compiling for and downloading to.

How do I access which board in my scripts?

Some sections are for one or the other exclusively. Right now I'm using a #define at top of the script, but changing this to switch between boards not the best. For example, version control keeps on thinking I'm in a new branch when I'm not.


texts: Timer (or other) interrupt happens while servicing an interrupt - how to accurately handle the second one?

texts:
This seems like a simple question but I'm not finding an answer so far: at a high level, say I have a timer interrupt and some input interrupt. The input arrives, the ISR is entered, interrupts are (automatically by default?) disabled, I service the input (quickly!), but while that's going on a timer used for some other purpose fires. I don't want to miss that timer but because interrupts are disabled my input processing won't get interrupted for it.

I exit the input ISR and interrupts are (automatically?) re-enabled. Assuming the timer is uncomplicated (it wouldn't overflow twice during my input ISR) how do I accurately handle the fact that it overflowed during my input ISR and I "missed" it?

Would this differ if instead of the timer I simply had a second input2 that similarly might fire during my input1 processing (but would present a useful input long enough to process after input1, presuming I knew it triggered)?

I'm not looking to nest interrupts here, just to understand what happens when an interrupt happens during another ISR which has temporarily disabled them - do they pend and fire after the blocking ISR returns, or are they just lost?


texts:
I have two Arduino, one is to handle the Bluetooth communication and send a signal to the other Arduino, and the other to interpret the signal and display or hide an image on the E-ink display.

It work just fine when they both are connected through the USB. But when I connect a 9V battery to the Arduino running the E-ink, instead of the USB, the image is displayed and cleared (looping), as if the IF ELSE conditions are not there.

I have tested if it actually runs the method by adding delay to the showImg()-method, and that seems to work.

I have also tested with connecting the USB cable to the E-ink Arduino to a 5V charger, and the case is the same.

Image:

Bluetooth code:

int ledPin = 13;
int state = 0;
int flag = 0;

void setup() {
 pinMode(ledPin, OUTPUT);
 digitalWrite(ledPin, LOW);

 Serial.begin(9600);
}

void loop() {

 if(Serial.available() > 0){
 state = Serial.read();
 flag=0;
 }

 if (state == '2') {
 digitalWrite(ledPin, LOW);
 if(flag == 0){
 Serial.println("Screen: off");
 flag = 1;
 }
 }

 else if (state == '1') {
 digitalWrite(ledPin, HIGH);
 if(flag == 0){
 Serial.println("Screen: on");
 flag = 1;
 }
 }
}

E-ink code:

#include <epd.h>

int displayed = 0;
int val = 0;

void showImg(void)
{
  Serial.print("showImg");
  displayed = 1;
  //epd_clear();
  epd_disp_bitmap("PIC9.bmp", 0, 100);

  epd_udpate();
  //delay(10000);
}

void clearImg(void){
  Serial.print("clearImg");
  displayed = 0;
  epd_clear();
  epd_udpate();

}

void setup(void)
{
  //Serial.begin(9600);
  epd_init();
  epd_wakeup();
  epd_set_memory(MEM_TF);
  pinMode(7, INPUT);

}

void loop(void)
{
  val = digitalRead(7);

  if(val == 1){

    if(displayed == 0){
      showImg();
    }

  }else {

    if(displayed == 1){
      clearImg();
    }
  }
  //Serial.println(val);
  //delay(3000);
}

I am a beginner when it comes to Arduino, So I hope someone can give me some hints to what may be wrong.

Thanks!


texts:
#include <Servo.h>

Servo esc;

void setup(void) {
  esc.attach(7, 1000, 2000);

  if (esc.attached()) {
    // this always runs
    // even if there's no servo connected to pin 7
  }
}

I've written code kind of like the above.

The problem is that after using Servo.attach the method Servo.attached always returns true, even if there's nothing in the pin that I've attached to.

How can I check if the pin, in this case 7, actually has a wire in it?


texts: Arduino Nano Update failure - avrdude: stk500_recv(): programmer is not responding

texts:
Before I tear all my hair and teeth out, can anyone please help. I have tried googling an answer and have not found anything.

My Setup:

Win7 64bit
Arduino 1.6.9 IDE freshly reinstalled
COM14 port in Arduino IDE checked
Under Device Manager COM14 shows as: "USB Serial Port (COM14)". Not as "Arduino...(COM14)" as some pages have shown
I am not sure if I have a real or copy of the Arduino. As far as I can figure out I have a real one, on the back I have the FT232RL chip
I have bought 2 Arduino Nanos and both show same error
Both Nanos came pre-soldered, (no noob soldering by me)
I have tried uploading sketches on my Win7 platform AND over a Raspberry Pi, both same error

Now perhaps most importantly I previously ordered an Arduino from the same retailer and that one worked. The two I have now dont work.

The problem:

When I try upload I get the same message every time: avrdude: stk500_recv(): programmer is not responding

a. it does this 10 times and then fails

b. Rx and Tx LED's are ON and do NOT blink at all at any point in time

c. Green power LED is always ON, no blinking

d. Pin13 LED blinks consistently

e. I have tried the extreemly annoying reset "trick" before uploading, after uploading, at the same time, during uploading, and nothing works

I am seriously at a loss here. I have had an Arduino Nano work on my pc.

Any help would be greatly appreciated please.


texts: Is there a way to define an alias for a hardware Serial

texts:
I'm porting some code from Arduino Uno over to a Mega and I want to replace a SoftwareSerial defined in the previous code with one of the built-in UARTs.

Rather than go through and replace all references to the serial port, I'd prefer to create an alias for Serial1. The alias can be a constant.

In my old code, I setup the Software Serial as follows:

//SoftwareSerial HMI(HMIRX, HMITX); // Define software serial for the HMI adapter (RX, TX)

I"m not even sure where to start.


texts: Atmega 328PU crash on 5v/1A. Why? It works on 5V/400ma but when i switch it to 5V/1A power it crash. Any idea or solution for this?


texts:
Arduino will not recognise USB ports on my Mac running Sierra
I am a teacher who helps teachers to use LilyPad. I used to be able to plug in my LilyPad Arduino and see the USB port. I have read all the answers and dowloaded the drivers from Spark fun and another driver from Github. Nothing is working and i am not technical enough to find the answer myself.  I have spent three hours today trawling through the answers to this problem and still cannot fix it myself. I am a luddite who needs a simple step by step remedy. Apple support had no idea when I rang them and told me it was an Arduino problem and to talk to them. you cant talk to anyone at Arduino you can only go to the forums. the forums tell you to read others answers before you post. I have. it's still not working. i need help. And not a lecture about being on a forum asking dumb questions.

I even mucked around in terminal and am hoping it's not a 'terminal" problem because I have no clue what i am doing. If you can explain in plain speak please respond. i have to teach this stuff in 4 days.

This is the message I get when I try to upload a sketch


texts:
I want to make either an alarm clock or countdown timer whose alarm is loud enough to notice, but soft enough to not wake me up when asleep. My idea is to use the sound of an analog clock that I have - powered by a single AA 1.5V battery. I like this sound. So, I'd like to create an alarm or a timer that can turn on the power to this analog clock for a few minutes at least. Ideally, it would be something I could use daily for a couple hours without replacing the timer/alarm battery too often.

I've looked at these programmable relay timers: http://www.amazon.com/dp/B00P0TZ5CY/ but the voltage seems kindof overkill.

I've also considered an arduino board, but I'd like to be able to set the time on the device without plugging it into a computer.

I'm a developer, so I could do arduino programming if needed, but I don't know much about circuitry & hardware. I've also never done an arduino project, so I'm starting from 101.

Any ideas where I could start? The timer I mentioned above would be perfect if it didn't require 12V power. My knowledge is limited, so maybe that's less of a big deal than I think.


texts: Connecting DAC output from Arduino Due to another arduino

texts:
I have an Arduino Due and I want to connect the output from the DAC as an input to an Arduino Uno's analog input pin. From this link http://forum.arduino.cc/index.php?topic=164763.0, user DuaneB suggested that a resistor should be used in series with the DAC output to prevent an excessive flow of current that could damage the pin. But he was talking about this when the question was about powering a motor using the current generated from the DAC's voltage.

However, is this series resistor required when simply connecting the output of the pin to the input of another pin? I haven't seen any issue when connecting the output of my Raspberry Pi's GPIO to an arduino's input.


texts:
Can some one explain this behaviour please, i have the following code

  byte buffer[512];
  byte block;
  byte len;

  Serial.setTimeout(60000L) ;     // wait until 20 seconds for input from serial
  // Ask personal data: Family name
  Serial.println(F("Type text followed by #"));
  len = Serial.readBytesUntil('#', (char *) buffer, 500) ; // read from serial
  Serial.print(len);
  for (byte i = len; i < 250; i++) buffer[i] = '#';     // pad with #
  Serial.print(len);

This works but if i change the "for" line to any thing higer then 250 it stops working and there is a "buffer out of memory condition)

My question is why can't the for loop say the below as the buffer size is 512?

for (byte i = len; i < 512; i++) buffer[i] = '#';

Am i right in thinking it has something to do with  (Char *), i did copy this code from the example ardunio code and was jsut trying to incress the lenth of input it accpeted.


texts: How to create delays in AVR assembly language

texts:
Hi i'm new to AVR assembly language so i was trying to get delay function to create 1 ms , 100us, and 1us  delays to do that i need to figure out what to replace nop's with below here (mainboard arduino uno r3 ATmega328
Thank you.

"delay_ms%=:    nop                 ; code to replace  nop  \n"
"delay_100us%=: nop                 ; code to replace  nop  \n"
"delay_1us%=:   nop                 ; code to replace nop  \n"
"               sbiw r30,1          ; decrement ms count (r31:r30)\n"
"               brne delay_ms%=     ; loop to delay_ms while > 0  \n"
"               ret                 ; return from subroutine      \n"

The rest is below.

word millisecs;
Serial.begin(9600);
}
void setup() asm volatile(
"          ldi r16,0x3F    ; r16 = 00111111\n"
"          out 4,r16       ; set pins 8-13 as outputs in DDRB\n"
::: "r16");
millisecs = 1000;            // 1s blink delay
Serial.begin(9600);
}
void loop()
{
long starttime = millis();        // make a note of the start time

asm volatile(
// jump to "blink" - ie jump around the delay_ms subroutine
"            rjmp  blink%=        ; relative jump to 'blink' \n"
"          ldi r16,0x3F    ; r16 = 00111111\n"
"          out 4,r16       ; set pins 8-13 as outputs in DDRB\n"
::: "r16");

registers used:
r31 - millisecond count (lo byte)
r30 - millisecond count (hi byte)
r17 - 100 microsecond count
r16 - 1 microsecond count
Overall delay (ms) = r30:r31 * r17 * r16
---------------------------------------------------------------------*/
"delay_ms%=:    nop                 ; code to replace  nop  \n"
"delay_100us%=: nop                 ; code to replace  nop  \n"
"delay_1us%=:   nop                 ; code to replace nop  \n"
"               sbiw r30,1          ; decrement ms count (r31:r30)\n"
"               brne delay_ms%=     ; loop to delay_ms while > 0  \n"
"               ret                 ; return from subroutine      \n"


texts: Optimizing ext. SPI ADC for speed and verify the speed

texts:
So I have a project where I will be using an Arduino Leonardo and an external ADC (AD7980) to run a 16-bit (18bit) conversion and transmit it to the Arduino and then out on USB as fast as possible.

The AD7980 can run up to 1 MSPS, and I know I cannot reach that with the ATmega32U4 - but I want to know how to optimize my code for running it as fast as possible and how to measure it.

Right now my code is:

#include <SPI.h>

int CNV= 11; //Convert on pin 11
int Slaveselect=8;
int adcValue;
byte highByte;
byte lowByte;

void setup() {
  Serial.begin(115200);
  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV2 ); // 8 MHz rate
  SPI.setBitOrder(MSBFIRST);
  pinMode(Slaveselect, OUTPUT);
  pinMode(CNV, OUTPUT);
}

void loop() {
  digitalWrite(Slaveselect,HIGH);
  // SS always high to use 3 Wire mode without busy indicator
  digitalWrite(CNV,LOW);
  digitalWrite(13,LOW);
  digitalWrite(CNV,HIGH);//starts conversion
  digitalWrite(13, HIGH);
  digitalWrite(CNV,LOW); //starts to transmit MSB on data line
  digitalWrite(13,LOW);
  highByte = SPI.transfer(0x00);
  lowByte = SPI.transfer(0x00);
  adcValue = highByte << 8;
  adcValue = adcValue | lowByte;
  Serial.print("analog value =");
  Serial.println(adcValue);
  Serial.print('\n');
}

The datasheet for the ADC can be found here: Datasheet


texts: Clock drift - is the precision of the crystal the only culprit?

texts:
I've a wall clock (sorry, code's a mess, look for updateClockVars) which makes use of the Timezone library (and ultimately Time). Nothing fancy, call millis() every loop; turn to Hrs, Mins, Secs; display on LEDs.

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


texts: Arduino measuring high-voltage electric fence

texts:
I would like to know if someone has experience with measuring high voltages using an Arduino.
I know you can use resistors to lower the voltage, however.
I want to be able to measure the pulses of an electric fence used to prevent farm animals from escaping. These pulses are high-voltage and will not always be a similar voltage. I want to read these voltages, to scan for differences.
So, I wondered if someone has done something like that, and if the Arduino gets weird when it gets a voltage above 5V at a low amperage on its analog port.
--here some possible solutions for those wanting to know the answer--
-mostly based on comments and answers below-

Using resistors as a voltage divider while keeping an eye on the maximum spark gap distance and capacitive coupling.
using a transformer/coils to reduce the voltage.
using a high voltage probe to measure it.
using neon bulbs or other light sources to measure it.
charging a capacitor and measuring discharge time with high resistance(only works for the total power)

-this list is meant as a summary of what is discussed further ideas and solutions are still welcome-


texts: MIT "happy board" like shield for arduino

texts:
I'm working with the robotics lab at the university to try and find a replacement for the obsolete Handy Board.

We're considering purchasing arduinos because of their ease of use but we can't seem to find shields with compactly integrated capabilities as the handy board (DC motor outputs, analog/digital inputs and a physical interface such as knobs and buttons).

We did consider purchasing expansion boards but the final product would be too bulky.

Here are the complete specs:

  Allow direct control of at least 4 DC motors
  Accept digital and analog sensor inputs
  Simple UI (LCD, buttons/knobs)
  Be as compact as possible (including the batery)

Does any one know if such a thing exists?


texts: Arduino(s) not resetting on Serial connection lost / re-established - why?

texts:
it seems that I accidentally found a way to make my two Arduino nano clones run without resetting on serial connection close/reconnect. On one hand, this behavior is much closer to the desired behavior and on the other hand it feels hackish, because I don't know the cause yet.

The devices are still able to be flashed with new firmware

I assume that it has to do with the usage of socat as proxy for the devices in question. The described behavior was first observed after playing with socat. The command that finally worked for me:

/usr/bin/socat -s -d /dev/ttyACM3,b115200,cs8,parenb=0,cstopb=0,clocal=0,raw,echo=0,setlk,flock-ex-nb,nonblock=1 PTY,link=~/.pyduin/ttyACM3.tty,b115200,cs8,parenb=0,cstopb=0,clocal=0,raw,echo=0,setlk,flock-ex-nb,nonblock=1

An Arduino Uno with the exact same firmware/treatment does not show the same bahavior.

Any ideas what had gone wrong? And how to restore the default FTDI behavior?


texts: How to detect Genuino 101 from inside the code?

texts:
I am using a custom library for Arduino Mega which uses AES library for AES-128 encryption.

However, when I try to use that library in Intel Genuino 101 development board, it shows compilation error which is because the assembly language written in AES library was compatible with Atmel devices only.

And my question is whether there is a way, my code can automatically detect the GENUINO board by writing some sort of signature verification of this board and hence I can exclude the encryption part if it can successfully detect GENUINO 101.

For any queries, feel free to bug me, thanks.


texts:
I want to post data that I'm getting from the sensor every 5 seconds to my application in JSON format. Initially, I'm getting data as int and converting into String.

For example:

if data=15, it is converting into string.

String st=String(data);

Now I want to post st every 5 seconds.

    int S2 = http.sendRequest("PUT", "{\"itemId\":\"64006A962B71A1E7B3A0428637DA997C.327681\",\"item\":{\"Properties\":{\"AssetSensorDistance\":\"+st+\"}},\"operationType\":\"Update\",\"originalItem\":{\"Work_Order\":{\"ItemId\":\"64006A962B71A1E7B3A0428637DA997C.327681\"},\"Properties\":{\"AssetSensorDistance\":\"+st1+\"}}}");
    Serial.print("Sensor Status: ");
    Serial.println(S2);

st1 is the previous value, it is printing httpcode -2(invalid Syntax).

Can anyone help me with this issue?

Thanks in advance.


texts: What minimal resistance should be between an input and output pin not to burn Arduino?

texts: So, I'd like to put a button between input and output pins to read when button is pressed. What minimal resistance should I add to the scheme not to burn Arduino when the button is pressed? Does this value depend on Arduino model?


texts: what happens on Arduino power-on, and how long does it all take?

texts:
Here's what I think happens and how long it takes (FIXME means I don't know).  I'd like to end up with solid max times for everything if possible.

Power-on, input caps to the 328P begin charging and Vcc to the 328P rising

From the time it first comes to life, internal 328P hardware holds an
internal reset line low.

Vcc to 328P climbs past the power-on reset voltage threshold V_pot, which has
a maximum value of 1.6V (see the ATmega328P_datasheet_revision_DS40002061A.pdf
Table 29-11).  For a 9V battery with a typical internal resistance of 2 ohms,
the time constant with the ~100 uF of input capacitance on the Arduino
is RC = (2 * 0.0001) = 0.0002 s.  So this normally happens pretty fast,
but note that if additional loads are connected to the Arduino Vcc or Vin
things might take longer.

A reset timer on 328P begins running.  When it expires the internal reset
line will be released.  How long this timer will run depends on fuse settings.
For the default Arduino fuse settings the timer will run for about 65 ms.
For a 3.3V Arduino variant the typical time will be slightly longer (~69 ms).
See ATmega328P_datasheet_revision_DS40002061A.pdf Table 29-11 Chapter 9
for details.

The PD7 line of the ATMEGA16U2 chip on on the Arduino holds the external
reset line low past the point in time at which the internal reset is released,
which causes the EXTRF bit of the MCUSR register on 328P the 328P to end up
set (indicating an external reset).  FIXME: does it actually work like this
(hold it low longer)?  FIXME: How long exactly?

The external reset is released by the ATMEGA16U2

The bootloader on the 328P begins executing

The bootloader examines the MCUSR and finds that EXTRF is set, but WDRF
of MCUSR is not set.  It therefore quickly flashes the on-board LED several
times and the attempts to download a new program over the serial line.
This process takes about 1.6 s total.

The download attempt terminates with a watchdog timer timeout and consequent
watchdog timer reset.  The EXTRF bit of MCUSR remains set (it is sticky and
is only cleared by a power-on reset or explicit 0 write).  Time: pretty quick

The bootloader starts executing (again).  Time: pretty quick

The bootloader examines the MCUSR and finds that the EXTRF and WDRF bits
of the MCUSR are both set.  It interprets this to mean that the bootloader
just executed and terminated due to a watchdog timeout, i.e. it decides that
an upload attempt has already been made.  It therefore clears the WDRF flag
(since it thinks it probably set it itself) and jumps to the start of the
application flash instead of making an upload attempt.  Time: pretty quick

All the setup code required to provide the C environment your main()
program requires runs.  This includes for example copying global variable
intial values from flash to RAM, etc.  Time: FIXME?

main() begins executing.


texts:
I've made a dice roller (to make it easier to roll the dice) using an Arduino UNO and an LCD keypad shield but I can't get the correct numbers (1, 6 (7)) to show up, I've tried using int, float and everything in between. the buttons on the shield are connected to A0, can someone help me please?

#include <LiquidCrystal.h>
// select the pins used on the LCD panel
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

#include "DFRkeypad.h"
String line2 = "Press Select to roll"; // Scrolling line

// just some reference flags
//int stringStart, stringStop = 0;
//int scrollCursor = screenWidth;

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

// read the buttons
int read_LCD_buttons()
{
  adc_key_in = analogRead(0);      // read the value from the sensor

  // For V1.0 comment the other threshold and use the one below:

  if (adc_key_in > 1000) return btnNONE; // We make this the 1st option
  for speed reasons since it will be the most likely result
  // For V1.1 us this threshold
  if (adc_key_in < 50)   return btnRIGHT;
  if (adc_key_in < 195)  return btnUP;
  if (adc_key_in < 380)  return btnDOWN;
  if (adc_key_in < 555)  return btnLEFT;
  if (adc_key_in < 790)  return btnSELECT;

  return btnNONE;  // when all others fail, return this...
}

void setup() {
  randomSeed(analogRead(1));
  lcd.begin(16, 2);              // start the library
  lcd.setCursor(3, 0);
  lcd.print ("Catan Dice");
  lcd.setCursor(0, 1);

  // while(line2)
  //
  // lcd.print(line2);
  // break;
}

void loop() {

  //Dice
  byte DiceOne = random(1, 7);
  byte DiceTwo = random(1, 7);

  //local varables
  int buttonState = read_LCD_buttons(); // read the button pad
  int lastButtonState = btnNONE; // previous state of the button

  // the following variables are unsigned longs because the time, measured in
  // milliseconds, will quickly become a bigger number than can be stored in an int.
  unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
  unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers

  switch (buttonState)
  {
    case btnSELECT:
      lcd.clear();
      //Row, Colum
      lcd.setCursor (0, 4);
      lcd.print(DiceOne);
      lcd.setCursor (1, 4);
      lcd.print(DiceTwo);
      break;
  }

  DELAY(100)

  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonState);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH), and you've waited long enough
  // since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer than the
    debounce
    // delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;
    }
  }

UPDATE, i got it working now


texts:
i want to turn on an led with two buttons. If either of the buttons is pressed i want the led to turn on while the button is pressed and stay off if nothing is pressed. i have two sets of code, they both do the same thing, but the second set of code causes the led to stay in the on position even when nothing is being pushed and i dont understand why.. i am using pulldown resistors on both the buttons.

This is the first set of code that works properly:

class Button {

  public:

    int pin;
    int state;
    int location;
    int Speed;
    int Direction;
    int active;
    int prevstate;

    Button(int pin1, int state1, int location1, int active1, int previousState)
    {
      pin = pin1;
      state = state1;
      location = location1;
      active = active1;
      prevstate = previousState;
    }
};

Button button(7,0,0,0,0);
Button button2(8,0,0,0,0);
Button buttons[2] = {button, button2};

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

void loop() {
   if (digitalRead(button2.pin) == HIGH){
             digitalWrite(ledPin, HIGH);
          } else {
          // turn LED off:
          digitalWrite(ledPin, LOW);
          }
       if (digitalRead(button.pin) == HIGH){
             digitalWrite(ledPin, HIGH);
          } else {
          // turn LED off:
          digitalWrite(ledPin, LOW);
          }
}

this is the code i want to use but it is not working.. the led stays in the on position:

void loop(){
  for (int i = 0; i<sizeof(buttons); i++){
    if(digitalRead(buttons[i].pin) == HIGH){
          digitalWrite(ledPin, HIGH);
          } else {
          // turn LED off:
          digitalWrite(ledPin, LOW);
          }
    }
}

also if i change

if(digitalRead(buttons[i].pin) == HIGH)

to

if(digitalRead(buttons[0].pin) == HIGH)

the code works for the first or second button alone in the array.. but not both???


texts: How do I know when the connections is ready between Arduino and QSerialPort

texts:
I am trying to send data from QSerialPort to Arduino Mega 2560. The proccess always takes some time to establish the connection.

How do I know with QSerialPort is the connections is ready to send data?

I don't know how much time do I have to wait for that and it happens every time when I run the application.

The configuration of my QSerialPort instance is:

mSerialPort = new QSerialPort();
mSerialPort->setPortName("COM3");
mSerialPort->setBaudRate(QSerialPort::Baud9600);
mSerialPort->setDataBits(QSerialPort::Data8);
mSerialPort->setParity(QSerialPort::NoParity);
mSerialPort->setStopBits(QSerialPort::OneStop);
mSerialPort->setFlowControl(QSerialPort::NoFlowControl);
mSerialPort->open(QIODevice::ReadWrite);

I check the device configuration of COM port:

I also changed and play the Arduino delay but nothing changed.

I am sending to Arduino little piece of data. Example:

X100.10,Y10.23, H9999, ...others

And these data work when I am debugging the functions of my application. Everything is writting and work. So I am lost.

I hope all this information be usefull to give me an answer or at less some tips.


texts:
I have a 24CL256 external EEPROM, to which I wish to write 30,000 bytes of 8-bit data, reading from the built-in ADC of an ESP8266.

Here is my code:

void setup() {
  Serial.begin(115200);
  Wire.begin(D2, D1);
  Wire.setClock(400000UL);
  Serial.flush(); // flush the transmit buffer
  delay(100);
  Serial.flush();
  delay(1000);
}

void writeData(uint16_t *address) {
  uint8_t data = analogRead(A0) << 2;
  // ESP has 10-bit ADC, convert to 8 bit data
  Wire.beginTransmission(0xA0); // Address for I2C EEPROM
  Wire.write((*address) >> 8); // address of write pointer
  Wire.write((*address) & 0xFF);
  Wire.write(data >> 4); // MSB
  Wire.write(data & 0xFF); // LSB
  Wire.endTransmission();
}

void loop() {
  if(indx < 30000) {
    unsigned long currentMicros = micros();
    // 8KHz sample rate = sampling at 125uS
    if(currentMicros - previousMicros > 125) {
      previousMicros += 125;
      writeData(addr);
      addr += 2;
      indx += 1;
      Serial.println(indx);
    }
  }
}

The Serial.println() stops after a couple of 1000 Samples and resets ESP throwing error

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v4ceabea9

I suspect there is some timer issue, but I'm not quite sure. Any help is appreciated.


texts: Can stackable Arduino headers be automatically soldered?

texts:
I want to design an Arduino shield with stackable headers, so it will allow other shields to be mounted on top of it.

I was wondering if these could be soldered automatically. Neither wave nor reflow soldering seems to be an option. Wave soldering would leave solder on the pins so they won't fit in sockets, and for reflow (pin-in-paste) the long pins will completely pull the paste from the holes.
Is hand-soldering the only way (making the board more expensive), or is there still another way? Would it be a good idea to supply the shield with the headers not mounted to save cost?
Or shouldn't I assume the average Arduino user has a soldering iron?


texts: Why does the program size increase so drastically with these switch-cases?

texts:
EDIT: The problem is my op-code catch is op >= 0x20 || op <= 0x2F rather than op >= 0x20 && op <= 0x2F and so most of the switch-case was being optimised away!

This is a really difficult question to ask, because I cannot make a minimal-verifiable version of it as its own sketch.

For fun, I'm writing an ATtiny85 byte-code interpreter. It reads op codes from EEPROM and executes them. Keeping my eye on the program size, I've been completely stumped by what's happening in the following.
I really must stress though - I could not recreate this in a minimal sketch :(

//_mem[] is a uint8_t[] for RAM allocation
//_pMem is a moveable pointer to _mem[]
//NextByte() retreives the next byte from EEPROM

//Before this is if-else statements catching ranges of similar op codes
  ...
//This one catches similar math functions (mem op= num1):
  } else if (op >= 0x20 || op <= 0x2F) {
    uint8_t num1 = _mem[NextByte()];
    if      (op == 0x20) *_pMem += num1; //1A
    else if (op == 0x21) *_pMem -= num1; //1S

//For all other op codes:
  } else {

//These can mostly be ignored

    switch (op) {
      case 0x00: J(*_pMem);                                break; //J_
      case 0x01: _o = NextWord();                          break; //JA
      case 0x0A: ++_pMem;                                  break; //MI
      case 0x0B: --_pMem;                                  break; //MD
      case 0x0C: _pMem += NextByte();                      break; //MA
      case 0x0D: _pMem -= NextByte();                      break; //MS
      case 0x10: *_pMem = NextByte();                      break; //S_
      case 0x11: _mem[NextByte()] = _mem[NextByte()];      break; //CP
      case 0x12: *_pMem = _mem[NextByte()];                break; //V_
      case 0x13: _mem[NextByte()] = *_pMem;                break; //_V
      case 0x80: SV();                                     break; //SV
      case 0xFF: noHalt = false;                           break; //HT
    }

The program in total, when in this configuration, is 2030 bytes.
However, when I instead put just the two op codes, 0x20 and 0x21, into the switch-case, the program balloons to 2680 bytes! Code:

      //the if-else statement for 0x20 and 0x21 is completely removed
      ...
      case 0x13: _mem[NextByte()] = *_pMem;                break; //_V
      case 0x20: *_pMem += _mem[NextByte()];               break; //1A
      case 0x21: *_pMem -= _mem[NextByte()];               break; //1S
      case 0x80: SV();                                     break; //SV
      ...

Immediately, I thought "it must be something to do with replacing num1 with _mem[NextByte()] each time", but when I tried the same thing in the if-else configuration, it was only 2044 bytes.

Obviously there's waaay more code besides this out-of-context slice, and I'd be happy to share the whole sketch, but why does it even matter? I cannot imagine why there is a 600+ byte jump, other than maybe the logic behind the switch(). Hence I'm asking!
It's not as if it's suddenly using floating point or any other gotcha...

While trying to make a minimal sketch, the if-else and switch statement configurations were only several bytes different in size, even while propping up various parts with unoptimisable code.

Thank you for all your time.


texts: Seeed CAN Shield - Not receiving extended CAN-Message

texts:
I want to receive an extended CAN-Message. I send a extended CAN-Message, but nothing happens. Maybe somebody have an idea what the problem is..

It works with a standard CAN-Message.

Thanks in advance.

// demo: CAN-BUS Shield, send data
// loovee@seeed.cc

#include <mcp_can.h>
#include <SPI.h>

// the cs pin of the version after v1.1 is default to D9
// v0.9b and v1.0 is default D10
const int SPI_CS_PIN = 9;

MCP_CAN CAN(SPI_CS_PIN);                                    // Set CS pin

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

    while (CAN_OK != CAN.begin(CAN_250KBPS))              // init can bus : baudrate = 250k
    {

        CAN.init_Mask(0,1,0);
        CAN.init_Filt(0,1,0);

        Serial.println("CAN BUS Shield init fail");
        Serial.println(" Init CAN BUS Shield again");
        delay(100);
    }
    Serial.println("CAN BUS Shield init ok!");
}

unsigned char len = 0;
unsigned char buf[30];

void loop()
{
    CAN.readMsgBuf(&len, buf);    // read data,  len: data length, buf: data buf
    unsigned long canId = CAN.getCanId();
    Serial.println("-----------------------------");
    Serial.print("Get Data from ID: 0x");
    Serial.println(canId, HEX);
    Serial.println("Data content:");
    for(int i = 0; i<len; i++) // print the data
    {
        Serial.print(buf[i]);
        Serial.print("\t");
    }
    Serial.println("-----------------------------");
}


texts: Signal reading from existing snackmachine

texts:
So - i started a project at my civil-service. I want to fill a old snack-machine with things we need in the ambulance (bandages, cool-packs, etc.)

In order to get the current amount of everything without counting everything all these things should be stored in the snack-machine.
The Arduino should be attached to the signal wires of the machine. If a signal is firing (when a button is pressed) the microcontroller should decrease the current amount of the item in the connected database.. so it is easy to see if some product is running low.

The machine itself works with AC.
 now the problem: I'm not that professional with microcontrollers/hardware and this is my first big project.

If the Arduino is connected between the motherboard of the machine and the buttons the Arduino won't interrupt when something is pressed. I attached a picture of the circuit. (The only thing what's not on the picture are resistors between arduino and the buttons). The voltage on the wires is about 7.5-8 Volts alternative current.


texts: Using SIMCOM SIM800 as a Bluetooth SPP Client

texts:
I just bought a SIM800 module for my Arduino project and I found that I supports Bluetooth too. I have already worked with HC-05 and my Android phone.

I tried to play with this module and able to connect it successfully with my Android mobile. I am able to make a call using it, accept a call, etc. But when I tried to send text data using it (in SPP mode), I ran into problem.

I have an app called Bluetooth Terminal in my mobile with which I use to communicate with my HC-05. But with SIM800, I can't connect.

I have read all the AT commands which are used to make a SPP connection. Here's a screenshot of the PuTTy terminal where I tried to make the connection:

As you can see in the image, whenever I try to call

  AT+BTGETPROF=1

It never returns to me. I also tried the command with my Bluetooth visible in the mobile, but still no result.

Whenever I try to run the command or

  AT+BTCONNECT=1,4

My SIM800 goes into state 2 and I have to manually reset it.

Can someone please help me with this problem? I just want to use my SIM800 as a SPP client/server so that I can exchange text data with my Android APP.

Thanks in advance.


texts: Where can I find a central repository of all available Arduino libraries?

texts:
Currently; when I start a new Arduino project with some new hardware, the first thing I do is to look for 3rd-party libraries that bring Arduino support for this hardware.

The first places I look are:

The Arduino Playground
GitHub
Google

Generally I find either no support library or several different libraries (it's quite rare to find only one) in different locations with different levels of documentation, different levels of testing...

Once I have found the library I need (sometimes I need to try several), I download it to my Arduino libraries folder, I use it and I forget it.

I find this process cumbersome:

manual search with different possible options, not always well documented
manual download and install to Arduino libraries
no version control in the process (all versions of a library have the same name and thus cannot coexist in the Arduino library folder).

I wish there was a central repository with all available libraries for arduino, with:

description (supported hardware, supported boards)
source code
documentation
versions

And a tool (Arduino IDE or external) to access this repository at project build time.

A kind of maven for Arduino in fact.

I have seen several discussions once took place on Arduino forum, but it seems they led nowhere:

Arduino Libraries Census and Repository
Arduino Library downloader
Arduino Library downloader (2)

Are there other options, that are made it to something usable (from the community or individuals, why not)?


texts:
I'm trying to read data sent from my phone to arduino via HM-10 Bluetooth Module. I downloaded the app, I paired the module to phone but I can't read data.
If I just upload a blank sketch to arduino and open Serial Monitor, if I sent "1" from phone, it appears on the monitor, it's ok. But if I write Serial.begin(9600) in setup loop then noting happens and I can't see anymore the data from phone and Serial.read() is useless. Can you help me?

This don't work:

char incomingValue = 0;
int doorPin = 13;
void setup() {
  Serial.begin(9600);
  pinMode(doorPin, OUTPUT);
}

void loop() {
  if (Serial.available() > 0) {
    incomingValue = Serial.read();
    Serial.print("\n");
    if (incomingValue == '1') {
      digitalWrite(doorPin, HIGH);
    } else {
      digitalWrite(doorPin, LOW);
    }
  }
}

And with this I cand see to the Serial Monitor what I'm sending from phone but I can't read the character.

char incomingValue = 0;
int doorPin = 13;
void setup() {
 // Serial.begin(9600);
  pinMode(doorPin, OUTPUT);
}

void loop() {
  if (Serial.available() > 0) {
    incomingValue = Serial.read();
    Serial.print("\n");
    if (incomingValue == '1') {
      digitalWrite(doorPin, HIGH);
    } else {
      digitalWrite(doorPin, LOW);
    }
  }
}


texts:
I am using this TI device TCA9539 (http://www.ti.com/lit/ds/symlink/tca9539.pdf) with the pins A1 and A0 tied to ground resulting the write address to 0x74.

I don't have any issues writing to this device address and perform the necessary functions, however when I try to read registers using Arduino read functions, getting NACK there. Is 0x75 correct read address?

For second question:

Based on the device spec for read operation:

  Reading from a slave is very similar to writing, but requires some additional steps. In order to read from a slave,
  the master must first instruct the slave which register it wishes to read from. This is done by the master starting
  off the transmission in a similar fashion as the write, by sending the address with the R/W bit equal to 0
  (signifying a write), followed by the register address it wishes to read from. When the slave acknowledges this
  register address, the master sends a START condition again, followed by the slave address with the R/W bit set
  to 1 (signifying a read). This time, the slave acknowledges the read request, and the master releases the SDA
  bus but continues supplying the clock to the slave. During this part of the transaction, the master becomes the
  master-receiver, and the slave becomes the slave-transmitter.
  The master continues to send out the clock pulses, but releases the SDA line so that the slave can transmit data.
  At the end of every byte of data, the master sends an ACK to the slave, letting the slave know that it is ready for
  more data. When the master has received the number of bytes it is expecting, it sends a NACK, signaling to the
  slave to halt communications and release the bus. The master follows this up with a STOP condition."

This is the code I am trying to use,

Wire.begin();
Wire.beginTransmission(0x74); // start i2c transmission as write addr
Wire.write(0x01)              // the register i need to read from
Wire.beginTransmission(0x75); // start i2c transmission as read addr given

I believe the device I2C read and arduino library functions for read is not making sense to me. Has anyone used this device for read?


texts: Arduino IDE giving a blow to battery back-up of PC

texts:
When I have serial plotter open in the Arduino IDE with serial communication going on, the fans of my PC go full speed. On checking I found that Java(TM) Platform SE binary(32 bit) is using about 29% of the CPU.

This gives a big blow to the PC's battery back-up. Is there some way to reduce the CPU usage ?

  The IDE version I use is Arduino 1.8.4

OS : Microsoft Windows 10 Home (64 bit)

PC : HP Au620 TX (laptop)

processor : Intel i5 7th gen (7200)

RAM : 8GB


texts: Why are LED's receiving different voltages connected to Arduino

texts:
I have four LED's all connected the exact same way to four pins via four 150OHM resistors. (ignore the sensors, they are doing nothing currently) The code is very simple in the loop:

  digitalWrite(blue1, HIGH);
  digitalWrite(green1, HIGH);

  digitalWrite(blue2, HIGH);
  digitalWrite(green2, HIGH);

Here's a photo of the setup, notice how the LED's all light up differently. They are receiving the following voltages from left to right (2.48, 1.72, 3.02, 2.15):

Why is this happening and how do I get them all to light up the same?


texts:
I have made a simple circuit having an IR receiver and a Servo motor. Here is the diagram:

Red wire: power
Black wire: ground
Orange wire: digital signal
And here's the code:
#include <Servo.h>
#include <IRremote.h>
int receiver = 13;
IRrecv irrecv(receiver);
decode_results results;
Servo myServo;
int pos = 0;
void setup() {
  // put your setup code here, to run once:
  myServo.attach(9);
  Serial.begin(9600);
  irrecv.enableIRIn();
  myServo.write(0);
  delay(200);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (irrecv.decode(&results)){

    if (results.value== 0xC0000C){
      for (pos = 0; pos <= 90; pos += 10) {
        // in steps of 1 degree
        myServo.write(pos);
        delay(15);
      }
      for (pos = 90; pos >= 0; pos -= 10) {
        myServo.write(pos);
        delay(15);
      }
    }
  }
  irrecv.resume();
  delay(100);
}

It rotates the motor 90 degree and back when a button on a remote is clicked.
Here comes the problem: This is working perfectly when connected to my PC, but it doesn't when I connect it with my 9-volt (cuboid shaped) battery. The lights on the Arduino board still light up, but the circuit does nothing when I press the remote button.
I have also observed that the servo vibrates a little bit, but doesn't move.
Is this a problem in my circuit, or is it just that my battery power is low?


texts: using a digital pin on node mcu as an analog

texts: i want to use volte and current sensors (ZMPT101B and ACS712) on node MCU these sensors are analog but node mcu has on analog pin can i use digital D0 pin for voltage sensor?