texts: Stop time in Tkinter Stopwatch with a PushButton

texts:
So, my main goal is to make a stopwatch with Tkinter, in which time is stoppped with an external pushbutton

My void loop function in Arduino Uno is

void loop() {

if(digitalRead(BUTTON) == HIGH){
    Serial.print("E\n");
digitalWrite(LED, HIGH);

while(1){

 if(digitalRead(BUTTON) == HIGH){
  continue;
  }

if(digitalRead(BUTTON) == LOW){
break;}

        }
                               }

}

Basically, whenever the pushbutton is pressed I send via serial the message "E\n" and the arduino enters in an infinte loop that only breaks when the pushbutton stops being pressed (to avoid sending more than one message).

Then I have my Python code that reads the serial through the serial.readline() function.

Part of my Python code is (remember that i'm making a stopwatch and time is appearing in the screen - variable timer[i] is what saves the second and the ms):

def update_timeText():
    if (state):
       global timer
       # Every time this function is called,
       # it increments 1/100 of a second
       timer[1] += 1

      # Every 100 centisecond is equal to 1 second
       if (timer[1] >= 100):
           timer[1] = 0
           timer[0] += 1

       if arduino.readline() == 'E\n':
           print("FLAG\n")

       # TIME STRING
       timeString = pattern.format(timer[0], timer[1])

       # UPTADE THE LABEL WITH TIME STRING
       timeText.configure(text=timeString)

   # Call the update_timeText() function after 1 centisecond
   root.after(10, update_timeText)

The variable state goes True whenever I start the stopwatch (via a Tkinter button, but that's irrelevant for this case).

My problem, is that the program stops in the line

if arduino.readline() == 'E\n':

i.e., it only continues if I press the pushbutton. What I think that is happening, is that the .readline() continues waiting and waiting until it receives the message 'E\n'... I've tried with the .readline.strip() and also only .read() but none of them worked.

It is though very strange, because if the condition in front of If is not verified, it should just continue...

Any suggestion?


texts: Motor cutting out when using HC-05 Bluetooth module

texts:
I'm using an L293D motor driver chip along with an HC-05 Bluetooth module. The two work as expected separately - I can send a string via a Bluetooth terminal app on my phone to the HC-05 and I see it in the serial monitor just fine, and I can use the serial monitor to change the speed/direction of the DC motor without an issue. However, if I try to use the Bluetooth console on my phone to change the speed, the motor only spins for about a second before I lose connection with the HC-05 and it stops.

I think this is happening because the Arduino is tripping some breaker by drawing too much current to power both the HC-05 chip and the DC motor. Is this the case? Should I use an external battery pack to power the DC motor and L293D chip, and then keep the HC-05 connected to the 5V out line on the Arduino?

Thanks.


texts: Arduino TFMini Lidar sensors and speaker

texts:
I have this code for the TFMini Lidar sensors and Speaker. I Need help figuring why I'm using this calculation in my code and why if I removed it the lidar will not give me any measurement? (see below plz).
And my code now it's only one sensor is working pins (4,5) I don't know why the three of them don't work together.   Thanks in advance.
I took this code from the internet My coding experience is basic .
rx[i] = TFMiniOne.read();
if (rx[0] != 0x59) {
  i = 0;
} else if (i == 1 && rx[1] != 0x59) {
  i = 0;
} else if (i == 8) {
  for (j = 0; j < 8; j++) {
    checksum += rx[j];
  }
  if (rx[8] == (checksum % 256)) {
    *distance = rx[2] + rx[3] * 256;
    *strength = rx[4] + rx[5] * 256;
  }
  i = 0;
} else {
  i++;
}

Here is the complete code:
#include "Talkie.h"
#include "Vocab_US_Large.h"
#include <SoftwareSerial.h>
#include "TFMini.h"
TFMini tfminiOne;
TFMini tfminiTwo;
TFMini tfminiThree;

Talkie voice;
const int Speaker = 3;

//Declaring variables and constants

SoftwareSerial TFMiniOne (4,5);    //(RX, TX)
SoftwareSerial TFMiniTwo (6,7);
SoftwareSerial TFMiniThree (8,9);

void getTFminiData(int* distance, int* strength) {
  static char i = 0;
  char j = 0;
  int checksum = 0;
  static int rx[9];
  if (TFMiniOne.available()) {
    // Serial.println( "tfmini serial available" );
    rx[i] = TFMiniOne.read();
    if (rx[0] != 0x59) {
      i = 0;
    } else if (i == 1 && rx[1] != 0x59) {
      i = 0;
    } else if (i == 8) {
      for (j = 0; j < 8; j++) {
        checksum += rx[j];
      }
      if (rx[8] == (checksum % 256)) {
        *distance = rx[2] + rx[3] * 256;
        *strength = rx[4] + rx[5] * 256;
      }
      i = 0;
    } else {
      i++;
    }
  }
}

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

  //Initializing
  Serial.begin (115200);
  while(!Serial);                     //Wait for USB Serial Port to connect
  Serial.println("Initializing...");
  TFMiniOne.begin (TFMINI_BAUDRATE);

  //Initializing TFMini Sensors
  tfminiOne.begin(&TFMiniOne);
  tfminiTwo.begin(&TFMiniTwo);
}

void loop() {
  int distance = 0;
  int strength = 0;

  getTFminiData(&distance, &strength);
  while (!distance) {
    getTFminiData(&distance, &strength);
    if (distance) {
      Serial.print(distance);
      Serial.print("cm\t");
      Serial.print("strength: ");
      Serial.println(strength);
    }
  }

  delay(100);

  if (distance > 30) {
    digitalWrite(Speaker,HIGH);
    voice.say(sp2_ALERT);
    voice.say(sp2_F);
  } else {
    digitalWrite(Speaker,LOW);
  }

  if (distance > 20) {
    digitalWrite(Speaker,HIGH);
    voice.say(sp2_ALERT);
    voice.say(sp2_L);
  } else {
    digitalWrite(Speaker,LOW);
  }

  if (distance < 15) {
    digitalWrite(Speaker,HIGH);
    voice.say(sp2_ALERT);
    voice.say(sp2_R);
  } else {
    digitalWrite(Speaker,LOW);
  }
  delay(300);


texts: Using digital pin 11 for DMDCon and IR remote

texts:
I have a project where I would like to control a countdown clock using a remote with:

Arduino Uno R3 Development Board

Funduino Uno Protoshield Board

Freetronics Dot Matrix Display Connector

Arduino IR Reciever

Both the DMDCon and the IR use digital pin 11. Can these two share the pin 11 or is there a workaround of sorts?


texts: are 3 connections necessary for a push button?

texts:
I'm referring to the 5th circuit (see below screenshot) of the sparkfun manual came with the arduino uno. Instead of connecting all three of the (+) (-) and the digital pin to each push button, can I just connect the (-) through the resistor and the digital pin?

Also a side question, in terms of physics, you need two ends to be connected in order to create pressure for the flow of electrons, but the digital wire for each push button that goes out to the arduino board doesn't have its own ground wiring that suppose to create the pressure as a couple. How to cope with that in terms of electron flow?


texts:
this is my first project on an Arduino platform. My aim is to build up a door lock unlockable by playing a short melody on a one-octave piano keyboard. I think the idea is cool!
I'm thinking at everything, but I can't figure out how to make Arduino move something (which in my case would be the proper door lock). I thought about a little motor, but I don't know if it is or not  feasible...
To be clear, what I want to do is a simple door lock like this
(or even simpler) being moved from an Arduino program. How can I do that?


texts:
Looking at the documentation for the millis() function , it says:

  Returns the number of milliseconds since the Arduino board began
  running the current program. This number will overflow (go back to
  zero), after approximately 50 days.

How's this possible? Is Arduino detecting when millis() overflow then resets the value to 0? If so, how does it do it? I just want to know what exactly is going on under the hood with the variable that is being returned by the millis() function.


texts: ESP8266 I2C datasheet pins not the same as several examples

texts:
According to espressif datasheet of the ESP8266 it uses
MTMS (I2C_SCL) and GPIO2(I2C_SDA) for I2C.

However in several examples I've seen the typically use is GPIO(4&5) or GPIO(0&4) to connect to the I2C.
I guess all method works? but what is the real difference?


texts: How to find out the maximum used stack space?

texts:
I am creating an Arduino sketch which involves quite some classes, and I want to check if it will run on an Arduino Uno or Mega (2 KB vs 8 KB SRAM).

So far my global variables take up around 1,200 bytes, and I expect this will rise. However, beyond that I need to make sure the stack memory is not using up too much. How can I find the maximum used stack size?.

I can check manually by calculating the maximum function stack and calculating all parameters + local variables, but this is a very tedious job (especially since my application changes still a lot).

Or another way: I know it is possible to get the free space, but should I add this in 'strategic' locations or in the beginning of all functions and continue from there? (there will be many of them).

Or is there preferable some static way of checking this?

The application works within Visual Studio C++ as stand alone too, so maybe that helps for some solution.

I expect the stack size easily to be a few hundred bytes (which is quite a lot for the Arduino Uno SRAM).


texts: Arduino Bluetooth upload problem HC-05 v4.0

texts:
I upload code into arduino nano using a self-made PCB with bluetooth using this method. I was initially using Arduino Nano (chinese Clone, the one with CH340G) and Bluetooth module HC-05 (version 3.0) (Lets assume this bluetooth is BT1)

At command response for BT1

AT+NAME?
+NAME:H-C-2010-06-01
OK
AT+POLAR?
+POLAR:1:1
OK
AT+VERSION
VERSION:3.0-20170601
OK
AT+UART?
+UART:9600,0,0
OK

All the things were working perfectly till the new nano as well as latest version of bluetooth arrived.

Bluetooth problem: I was trying to configure the newer bluetooth BT2 and I faced the error highlighted in code.

AT Commands response for BT2

    AT+NAME?
    +NAME:HC-05
    OK
    AT+VERSION?
    +VERSION:4.0-20190815
    OK
    **AT+POLAR**
    **ERROR:[0]**
    AT+UART?
    +UART:9600,0,0
    OK

The problem I am facing is I am unable to change the state pin with AT+POLAR command. I think this version of bluetooth has different AT Commands. If anyone knows about this particular problem please help.

Also I tried uploading code using old bluetooth to a newer version of Arduino Nano (New bootloader OPTIBOOT) and it was successful. Needed to change the baud rate of program as well as Bluetooth to 115200.


texts: strcat appending multiple times when called in loop

texts:
The strcat function is working fine when called for the first time but when the broker goes down and it's attempting to reconnect it is appending the value twice. I am not able to figure out the problem as i am writing C code for the first time.

void reconnect() {

  while (!client.connected()) {
    const char* cid = clientID.c_str();
    if (client.connect(cid)) {
       const char* sTopic = strcat("clm/",cid);
       client.publish(outTopic, sTopic);
       client.subscribe(sTopic);
    } else {
    // Wait 5 seconds before retrying
    for(int i = 0; i<5000; i++){
      delay(1);
    }
  }
}

}

It is called in the loop method

void loop() {
  if (!client.connected()) {
    reconnect();
  }
}

The value of sTopic for the first time is clm/5C:CF:7F:3D:5B:F6 but when the broker restarts and the client connects again it is clm/5C:CF:7F:3D:5B:F65C:CF:7F:3D:5B:F6

What could be the reason for the same ?


texts: HC-05 Bluetooth module on breakout board with straight header pins

texts: Has anyone found the HC-05 bluetooth module (on the breakout board) with straight header pins?  I seem to only be able to find them with the 90 degree header pins.  Removing those and soldering on straight ones for my project is getting tiresome...  I would even be happy to find them without header pins (but still on the breakout board).


texts: How do I program an LCD screen and do I need an Arduino

texts:
I am trying to create a small device with a screen that tells the date and time. I am thinking of using a UCTRONICS 0.96 Inch OLED Module (type that on Amazon). I am very new at coding, and I know more about electrical engineering, so I have a few questions.

Do I need an Arduino that big to power this screen or any screen? I am trying to put this in a compact housing

How do you set up the screen and code it to tell the time and date

Is there a better screen for me to pick that is easier to work with, or is there a screen that comes programmed telling the time and date

Can someone help, please?


texts: Control 12V power with 3 transitors to 3 seperate consumers

texts:
I have this shematic. With one electrical Pump and two solenoid valves I want to control via the arduino.

Here are the specs for the parts:

Pump: 12V max. 250mA
Valve 1: 12V max. 160mA
Valve 2: 12V max 220mA
Source: 12V max 2A

simulate this circuit – Schematic created using CircuitLab

My questions is:

Are the 4.7k resistors enough?
Do I need different resistors for the different consumers?
And I am using S8050 as transistors. Are they to small for the load?
And where do I have to connect the ground of the arduino to?


texts: Strange behavior on 74HC595 Shift Register IC when its GND pin is used

texts:
I was following a tutorial similar to this:
https://www.arduino.cc/en/Tutorial/ShiftOut

That is, an array of 8 LEDs that lit up accordingly to the binary representation of a number, which was given in a loop from 0 to 255.

The problem is that when invoked shiftOut() over certain numbers (such as 5, 9 or 13), the LEDs didn't lit as expected.

I even tried replacing the IC, but what finally solved this issue was to disconnect IC's pin 8 (GND) and let only pin 13 (OE) connected to Arduino's ground pin.

Does anyone know the reason this strange behavior happens on 595 IC?

Here's a video showing the circuit finally working (without IC's GND pin connected): https://www.youtube.com/watch?v=NGfpk-kjemo


texts: Arduino tool to enumerate where RAM is being used?

texts:
In a sketch I have, I use a few libraries and have discovered that a large amount of RAM is being consumed.

Is there a tool that can identify how this RAM is being allocated, e.g. which libraries, which piece of code?


texts:
I have edited the adafruit ST7735 library so that it supports esp-32.I made some edits in Adafruit_ST7735.h file. which are as follows.

The code works fine but I had expected the screen to work faster with esp-32(due to higher processing power) but it does not do that.

I checked the time for fill screen operation for esp-32 and arduin mega. They come out to be almost the same. (around 0.12 seconds). Can anyone explain why this is happening and can I increase the speed?


texts: Buying Arduino Parts Different Manufacturers

texts:
I'm looking to buy my first arduino kit. However I have a concern.

If my Arduino Mega is bought from one manufacturer, then can I buy shields or other parts from other manufacturers? Are there any incompatibility issues

Thanks!


texts: I got a chinese SIM900a module but it can't connect to the network (I live in Europe). Is there a way to get it work on Europe mobile networks?


texts: error with avrdude command line using arduino as isp (i think)

texts:
I am trying to upload a .hex file to my attiny85v-10pu and using my arduino as a isp (i think thats the right term) but it come up with this error.

ser_open(): can't open device "lpt1": The system cannot find the file specified

I put in the command avrdude -c arduino -p attiny85 -u flash:w:tvbgone.hex

I am using cmd on Windows 10 and am following a tutorial on instructables and am using an attiny85v-10pu with an arduino as a programmer.

please help before my brain explodes :)


texts:
So I am trying to use Port Manipulation to turn on LEDS but I need to use PORT Manipulations for specific reasons.

//22-29PORTA (0x01-0x80)
//30-37PORTC (0x80-0x01)
//38-45PORTD (0x80-0x01)

void setup(){
PORTA =  B0000000; //29--->22
PORTC =  B0000000; //37--->30
PORTD =  B0000000; //45--->38
}

void loop(){
 PORTA =  B1000100;
 PORTC =  B0101000;
 PORTD =  B0000010;
 delay(1000);

 PORTA =  B1010000;
 PORTC =  B0001010;
 PORTD =  B0100000;
 delay(1000);

 PORTA =  B0010100;
 PORTC =  B0100010;
 PORTD =  B0001000;
 delay(1000);

}```
Heres the code for Arduino Mega 2560


texts:
I am working on a code including interrupts. They, however, refuse to work, even in this simple code that could be the most basic example of interrupts.

In this simplified extract I have a momentary push button attached to an Arduino Pro Mini's PIN 2, with the other side grounded. I have this code uploaded:

#include <Encoder.h>   // is this library the cause??...

#define PIN_1 4
#define PIN_2 3 //interrupt pin    //using these for a rotary encoder, not in this extract
#define PIN_B 2 //interrupt pin    // the rotary encoder also works as a push-button

void setup() {
  pinMode(PIN_B, INPUT_PULLUP);
  Serial.begin(9600);
  attachInterrupt(PIN_B, ButtonPressISR, FALLING);
  attachInterrupt(PIN_B, ButtonReleaseISR, RISING);
}

void loop() {
  Serial.println("Don't interrupt me");
  delay(10);
}

void ButtonPressISR() {
  Serial.println("Yay, I'm pressed!");
  delay(1000);
}

void ButtonReleaseISR() {
  Serial.println("Yay, I'm released!");
  delay(1000);
}

One would expect that without action, the Arduino floods the serial console with "Don't interrupt me". And that's correct.

When I press the button, however, nothing on Earth happens, neither of the interrupt service routines starts. No matter how hard I try, "Yay, I'm pressed" and "Yay, I'm released" never appears on the console output, and the 1 s delay never happens.

The circuit, shown below, is tested with a multimeter, and is error-free. Pin 2 does get pulled down, and back, upon button press/release.

simulate this circuit – Schematic created using CircuitLab


texts:
I'm not expert about web development but very excited of doing some rest call using the yun as server (with a minimal python or node.js server inside the openwrt machine in the yun) and expose sensors and actuators to the cloud.

I'm also worried about security. I don't want the super-shellproof system but just don't want that accidental visitors reads my home temperature or make my garden light switch on when I'm out.

For instance I have a central unit yun with some logic inside it and few arduino yun that makes reads from sensors and runs actuators around my home. The communication between the central yun and the slaves is happening via REST calls. I'm using curl for testing it, for instance. Here two questions:

Arduino Yun provide a simple user/password account when arduinoname.local/arduino is called. How is it implemented?
Let's say I'm using node.js to make a super simple web-server, what is the best way to protect the communication central-yun and slave-yun? and to protect central-gun and internet communication?

Best way in term of computation (the yun machine is not very powerful and I'm going to use battery in some cases) and in term of "easy to implement".


texts: Using Arduino audio to control an LED light

texts:
I am looking for a way to control an LED on a circuit board using audio input for learning purposes.

I have written my own speech recognition system using dynamic time warping in Python, but I would like to know if (and maybe what models if not all can do) Arduino can possibly handle the processing of a 70 by 70 O(n^2) matrix traversal with fft or dct operations on audio input divided into 10ms frames.

Any advice will be appreciated.


texts: Why do sketches take up so much space and memory?

texts:
When I compile this sketch for the Yún:

int led = 7;

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

void loop() {
  digitalWrite(led, HIGH);
}

I get:

  Sketch uses 5,098 bytes (17%) of program storage space.

  Maximum is
  28,672 bytes. Global variables use 153 bytes (5%) of dynamic memory,
  leaving 2,407 bytes for local variables. Maximum is 2,560 bytes.

Even when I compile the BareMinimum sketch:

void setup() {
  // setup
}

void loop() {
  // loop
}

I get:

  Sketch uses 4,548 bytes (15%) of program storage space.

  Maximum is
  28,672 bytes. Global variables use 151 bytes (5%) of dynamic memory,
  leaving 2,409 bytes for local variables. Maximum is 2,560 bytes.

Why does a bare minimum sketch take up 15% of the program storage space allocated? And why does a very simple sketch take up 17% of the program storage space? According to the Arduino website:

  It's easy to use it all up by having lots of strings in your program.
  For example, a declaration like: char message[] = "I support the Cape
  Wind project."; puts 33 bytes into SRAM (each character takes a byte,
  plus the '\0' terminator).

However, there aren't any strings declared in either of these sketches.

It seems as if they might import or use other libraries/classes that I don't specify. Maybe it imports a system default library? Or is it something else?


texts: How to pass a static const (progmem) array to a function

texts:
I'm implementing a voice synthesizer chip. To build a phrase, I create a list of phonemes like this:

static const uint8_t PROGMEM heybuddy[] = {
  pPA5, pHH1, pEY, pPA5,
  pBB2, pAX, pDD2, pIY, pPA5,pPA5,pPA5,
};

And to play them I do this:

 for (size_t i=0; i<sizeof(heybuddy); i++){
    say(pgm_read_byte(heybuddy+i));
 }

So what I'd like to do is create a function where I can just pass the array to a function that can take care of the loop and do some other maintenance stuff.

//what I've tried:
void sayPhrase(const uint8_t *phrase){
  int open = 0;
  for (size_t i=0; i<sizeof(*phrase); i++){

      if(pgm_read_byte(*phrase) != 4 && open == 0){
          Serial.println("mouth open");
          open = 1;
      } else if(pgm_read_byte(*phrase) == 4 && open == 1){
         Serial.println("mouth closed");
         open = 0;
      }
      say(pgm_read_byte(*phrase+i));
    }
}

But when it comes to passing a static const I'm lost I've tried passing it as a reference with * but nothing I do seems to work - I just don't know the proper way to do this in C.

What I have compiles, but it seems to only get one phoneme and repeat it over and over. The rest are lost.


texts: How do you connect parts once all GPIO ports are used?

texts:
I have a rather ambitious project in mind. Lots of buttons, sensors, feedback.

If I run out of GPIO ports to attach stuff to my Arduino, what's next? Do you have to buy a separate Arduino to run the extra parts, and then link the two arduinos somehow?

Thanks for any direction you can give.


texts: Simple Arduino Bluetooth Shield Android Display

texts:
I need help with my Arduino code. Here is my setup:

LM35 connected to Arduino with output connected to Analog 0.

Temperature computation work and serial monitor displays the correct reading.

I want to connect via Bluetooth to an Android app to display the temperature.

It displays it a few times but 98% of the time it doesn't display it on the app. I'm thinking the problem may be in the code that I have:

#include <SoftwareSerial.h>

#define RxD 6
#define TxD 7

float temp;
int temperaturePin = 0;
float  temp1;
SoftwareSerial blueToothSerial(RxD, TxD);

void setup() {
  Serial.begin(9600);
  pinMode(RxD, INPUT);
  pinMode(TxD, OUTPUT);
}

void loop() {
  temp = analogRead(temperaturePin);
  temp1 = temp * 0.48828125;
  Serial.print(temp1);
  delay(1000);
  blueToothSerial.print(temp1);
  delay(1000);
}

I just really want to make it simple. Kindly help.


texts: How to split a *char and pass to a function needing uint8_t?

texts:
I have a requirement where an event has char *newvalue.

void event(char *newValue) {
//Code here
}

newValue is 2 digits. If it's 1-9 it is " 1" " 2" and 10+ is "10" "11" etc. It also can contain alpha characters as well not just numbers.

I am passing this to a function void function(uint8_t ascii) to display on a single digit display. If I pass newValue it doesn't register less than 10 as it picks up the space.

So what I am trying to achieve is if it's a single character, strip the space somehow into a uint8_t and if it's 2 digits strip just the right digit as a uint_8 and have a bool where I will turn on the decimal point.

I've googled like crazy and can't seem to get something workable. If somebody can help it would be appreciated. If the above is not clear please let me know what more info you need.

The code below, 'value here' is where I want to put the rightmost value from *newvalue.

void onUfcComm2DisplayChange(char *newValue) {
  comdisp.setBrightness(9);
  comdisp.writeDigitAscii(0, 'valuehere');
  comdisp.writeDisplay();
}

void Adafruit_AlphaNum4::writeDigitAscii(uint8_t n, uint8_t a,  boolean d, boolean w) {
  uint16_t font;
  if (w == false) {
    font = pgm_read_word(alphafonttable + a);
  } else {
    font = pgm_read_word(alphafonttableWD + a);
  }
  displaybuffer[n] = font;
  if (d) displaybuffer[n] |= (1 << 14);
}


texts: How can I give power to Arduino Uno using a 12V 7.5 Ah Lead-Acid battery?

texts:
I am trying to give power to my Arduino Board using a 12V 7.3 Ah Lead-Acid Battery but I am unable to do it.

I connected the battery to Arduino Uno (via DC Pin) and it worked for a couple of minutes but then, it automatically stopped working. I checked the voltage of the battery using a Multimeter from the same DC Pin which was connected with battery and board. The voltage was 12.62 volts.
Then I thought my board might have been fried. So, I checked the board by connecting it with a 12V 2 Amp DC adapter and I found that my board was not fried and it was working fine with the Adaptor. The Adaptor was giving 12.48 volts voltage. Then, I again checked the board using battery but still it didn't work. I tried charging the battery via a charger but it still didn't work. I tried these steps multiple times but the results were always same.

I checked with my 12V DC Fan & some other devices also and it works perfectly, but it doesn't work with my Arduino Board.
This indicates that my battery is in a good condition but not working with Arduino Board only. While Arduino is also in a good condition, working with 12V DC Adaptors but not with the Battery.

Please Help!


texts:
I am a beginner and I want to learn AVR C/C++. Can I do this using an Arduino?  (I'm asking this because I already have one).

If so, could someone tell me using which IDE can I write code in pure C/C++ and then flash it to the Atmega328P on the Arduino?  Or, should I get an AVR and a programmer instead?

I've searched all over the internet and I'm really confused by all the terminology. Could someone explain it to me?


texts:
I've been using the pulseIn() function for processing PWM-based binary data encoding. It works well for distinguishing pulses which are significantly different lengths, e.g. 500us vs. 1500us. That makes it more than sufficient for handling typical IR remotes.

However, I want to make my own IR system which can use more than 2 pulse lengths, so that data transfer can occur faster. Ideally, I'd like to use 8 different pulse lengths for octal encoding (e.g. 200us, 400us, 600us, etc.).

I've noticed quite significant variations in the values returned by pulseIn() though (+/- 10%). I expect at least some of it is introduced by the IR transmitter and receiver modules, but I don't have good enough equipment to verify that.

Assuming I can mitigate that external error, is pulseIn() likely to be precise enough to distinguish such similar pulses?


texts: Multiple external power sources and one Arduino

texts:
really noob question..
I am thinking of using a 12v power source and a 5v power source as an external power supply for my 5v relay (and some other stuff that I might add up to my project that will need 5V) and the 12v is for my 12V solenoids.
Is it right to connect all ground wires to the ground of the Arduino?
I am really sorry that I have to ask this question cause all tutorials I see online are only connecting one external power supply to their Arduino.
Any form of correction is highly appreciated. Thank you so much


texts: HobbyTronics UNO PRO Board Definition does not work in newer IDE versions

texts:
I have a HobbyTronics UNO PRO that replaces the UNO's 328P in DIP with an ATMega1284 on an adapter board:

I cannot link to the original page since it does not exist anymore.  But, it is available through archive.org.
The original board definition, supplied by the distributor, stopped working after 1.8.10 and throws errors in 1.9.
The particular error when trying to compile:
recipe.preproc.macros pattern is missing

It is not about a particular library or similar; I cannot compile at all (even an empty sketch).
How can I migrate this board? I'd really like to use a current version of the compiler & IDE.


texts:
I am writing a program to emulate a LCD driver chip (PCF8576) in a piece of equipment where I need to replace an unobtainable LCD display.

I have wire.h set up and the code in place to decode chip commands and load the segment data to an array.  That all works, and I can take that data and drive a new LCD just fine.

My problem is that the onReceive handler only triggers once.  To get it to be armed and trigger again I need to press the reset button on the Uno board.  I put code in to pulse an output pin and can verify with a scope that the onReceive only runs once.

When I just began the coding last week the handler would trigger each time the equipment would write to this particular I2C address, and I can tell the equipment is operating correctly since an Arduino reset will then result in the onReceive event triggering again.

Does anyone have any clue what's happening here?  I tried commenting out most of my code but it still won't trigger on each receive.  Obviously there's something subtle I changed that I'm missing, but what?


texts: Linear equation solver Arduino Calculator, printing wrong answer

texts:
I wrote a code in C to solve equations, but I don't know why some equations that I input into this calculator, give me wrong values, the algorithm is correct because I execute it in C and give me the correct answers but when I use it on the arduino sometimes it doesn't give me the correct answer, well here's the full code https://mega.co.nz/#!BFt0FLLA!S5xUtvbmZT6PKyyVSdKO5smDCMyQiqTnCY_qM8Y48yo and here are the important parts of the code:

 #include <LiquidCrystal.h>
 #include <Keypad.h>
 #include <SPI.h>
.
.
.
.
declaration code and variables
.
 void(){
  nothing interesting here
  }
 loop(){
  valuereturned=entrada();
  .
  .
  .
  here's more code
  .
  .
  a few loops for reading
  .
  .
  jordan();
 }
 /*this part is for reading the numbers from keypad maybe here's the problem*/
int entrada(){
int flag=0,flag2=0,ent=0;
long lgtd=0,numero=0;
double rnum=0,numero2=0;
String num="";
      char key=keypad.waitForKey();
ctt=0;
while(key!='#'){
      switch (key){
             case NO_KEY:
             break;

             case 'A':
             loop();
             break;

             case '.':
             if(ctt<=8){
             num=(String)numero;
             lgtd = num.length();
             if(numero==0){
                  lcd.setCursor(0,1);
                  lcd.print("0.");
             }else{
                  lcd.setCursor(lgtd,1);
                  lcd.print(".");
             }
             flag2=1;
           }
           break;

     case '0': case '1': case '2': case '3': case '4':
     case '5': case '6': case '7': case '8': case '9':
        ctt++;
        if(ctt<=8){
           if(flag2==0){
              lcd.setCursor(0,1);
              numero = numero * 10 + (key - '0');
              lcd.print(numero);
           }
           if(flag2==1){
              ent++;
              lcd.setCursor(lgtd+ent,1);
              lcd.print(key-'0');
              numero2 = numero2 + ((key - '0')/(pow(10,ent)));
           }
         }
        break;

     case '-':
      lcd.setCursor(15,1);
      lcd.print("-");
      flag=1;
     break;

     case '\n': /*clearing and erasing*/
        numero=0;
        numero2=0;
        flag = 0;
        flag2=0;
        ctt=0;
        ent=0;
        lcd.setCursor(0,1);
        lcd.print("                ");
        break;
  }
     key = keypad.waitForKey();
 }
  rnum=numero+numero2;
  if (flag==1){
     flag=0;
     rnum=(-1)*rnum;
  }
  lcd.setCursor(0,1);
  lcd.print("                 ");
  return rnum;
 }

int jordan(){ /*This part solve by gauss, and It works fine on the pc*/
  int FilaMax,k;
  double maxEl,tmp,fracc;
   lcd.clear();
for (colum=0; colum<cant-1; colum++) {
    /* Busca la Maxima Columna*/
    maxEl = abs(a[colum][colum]);
    FilaMax = colum;
    for (k=colum+1; k<cant; k++) {
        if (abs(a[k][colum]) > maxEl) {
            maxEl = abs(a[k][colum]);
            FilaMax = k;
        }
    }
    /* Se hace el intercambio de la maxima fila con la actual*/
    for (k=colum; k<cant+1;k++) {
        tmp = a[FilaMax][k];
        a[FilaMax][k] = a[colum][k];
        a[colum][k] = tmp;
    }
    /*Aqui se realiza la triangulacion inferior de ceros*/
    for (k=colum+1;k<cant; k++) {
        fracc = -a[k][colum]/a[colum][colum];
        for (fila=colum; fila<cant+1; fila++) {
            if (colum==fila) {
                a[k][fila] = 0;
            }else{
                a[k][fila] += fracc * a[colum][fila];
            }
        }
             }
}

    /*print solutions or print that there is no solution*/
   .
   .
   .printing code goes here
   .
   .
   return 0;
 }

Try the code with this:

 input:
    # size
    4
    elements:
    1 -2 1 1 2
    3 0 2 -2 -8
    0 4 -1 -1 1
    5 0 3 -1 -3
 output:
 some numbers

 it should print without solution.


texts: Need help with using pulseInLong to time a sensor

texts:
I have a setup consisting of a magnet suspended above a sensor coil. It acts as a pendulum and creates a ~ 4 mV signal when it swings over the coil - this goes through two stages of an LM358 to generate a 5V signal. The signal is very messy with lots of 'ringing'
This signal is fed into pin A0 of an Arduino Uno. I used MegunoLink.h and Filter.h which is an exponential filter library then applied constrain and map, finally converting to a clean 0 - 400 (units?) square wave of about 1 second with a varying duty cycle. This is the information I want as it tells me that the magnet is homing in on the sensor (the duty cycle increases as it gets close).
But when I apply pulseInLong I only get a string of zeros on the serial monitor.
What am I doing wrong?
Here is the sketch:

//  Coding by Jeremy 130520
//  further development for ricochet module
//https://www.megunolink.com/documentation/arduino-libraries/exponential-filter/
//https://www.google.com/search?q=how+to+use+arduino+pulsein

#include "MegunoLink.h"
#include "Filter.h"
// Create a new exponential filter with a weight of 5 and an initial value of 0.
ExponentialFilter<long> ADCFilter(5, 0);

int coilPin = 8;
int analogIn = A0;
unsigned long pulseLength;
unsigned long signal_1;

void setup()
{
  pinMode(coilPin, OUTPUT);
  pinMode(analogIn,INPUT);
  Serial.begin(9600);
  }

void loop()
{
 int RawValue = analogRead(analogIn);
  ADCFilter.Filter(RawValue);
 signal_1 =(ADCFilter.Current());
 signal_1 = constrain(signal_1,80, 200);
 signal_1 = map(signal_1, 80, 200,0,400);
 if (signal_1 >= 200) {signal_1 = 400; digitalWrite(coilPin, HIGH);}
 if (signal_1 < 200) {signal_1 = 0; digitalWrite(coilPin, LOW);}

 Serial.println(signal_1); //using the plotter

//pulseLength = pulseInLong(coilPin, HIGH);
 //Serial.println(pulseLength);
 delay(10);
}


texts:
i have to make a network made of a master (made with controllino) and a slaves (also made with controllino) and they can comunicate with the modbus tcp protocol, i know that controllino works like a arduino with an ethernet shield but on the internet i haven't found any tutorial or articles that answer to my needs.
is there anyone that can tell me a libraries that can be good for my needs or a tutorial/article that tell me how i can made this network?
thanks if you answer me.

P.S. this video is similar to what i want to do, the only difference is that he use m-duino instead of controllino.

https://www.youtube.com/watch?v=4l0NpavwFIw&t=130s

for example i have foud this library "modbusip" that have the example "switch" but i don't know how to connect with anothe controllino that do the master, how can i do??


texts: How to make a dynamic menu with a sub-menu ( Arduino mega or Arduino Uno)

texts: I have an arduino mega with a LCD shield (from keyestudio KS2056). I am trying to create a menu with a submenu that would have addable and removable strings based on inputs from a RFID scanner(addable) and buttons(to remove selected strings). I am not so sure how I could possibly do this. Any assistance would be great.


texts:
I have ATMega328p chip, and I have HC-06 on pin A5, A4 (RX, TX) and I have another device on pin 10, 9 (RX,TX).

I want to be able to send some command on BT via Bluetooth Terminal and pass raw (exact) command to that device unchanged just to log on my computer (on my serial monitor) incoming command from BT and to log the response from device the same way on serial monitor and pass unmodified to HC-06.

How can I do that?

I tried by using "listen()" method but sometimes I get some weird character while I'm transferring\reading data, so not sure how to do this.

All baud rates are 9600.


texts: Proper use of * and & when passing objects in methods

texts:
Coming from C#, pointers are somewhat foreign although I am grasping the concept.
Is it proper to construct methods in the following manner and passing the object (as a parameter) constructed by reference? If not, then please answer how to do this properly.

Initialize the object

Adafruit_VS1053_FilePlayer musicPlayer =
    Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

Method: (use the * for pointer?)

boolean initializeMusicPlayer(Adafruit_VS1053_FilePlayer *mp, uint16_t baudRate) {

    musicPlayerSerialPort.begin(baudRate);
    // initialise the music player
    if (!mp->begin()) { // initialise the music player
        Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
        return false;
        //while (1);
    }
    Serial.println(F("VS1053 found"));

    mp->sineTest(0x44, 500);    // Make a tone to indicate VS1053 is working

    if (!SD.begin(CARDCS)) {
        Serial.println(F("SD failed, or not present"));
        return false;
        //while (1);  // don't do anything more
    }
    Serial.println("SD OK!");
    // Set volume for left, right channels. lower numbers == louder volume!
    mp->setVolume(20, 20);

    if (!mp->useInterrupt(VS1053_FILEPLAYER_PIN_INT)) {
        Serial.println(F("DREQ pin is not an interrupt pin"));
        return false;
    }
    return true;
}

Call the method (Use the ampersand to pass the currently created one by reference?)

if(initializeMusicPlayer(&musicPlayer, 9600) == true) {
    tempString = tempString + "MusicPlayer initialized!";
    Serial.println(tempString);
    //when adding lcd, print the above to lcd and remove the serial print
}


texts: Arduino IDE Board Manager: Unable to install Due on 1.6.5

texts:
I have an Arduino Due I'd like to start using. I've been using Unos, Megas etc no problem. The newer IDEs have removed the Due support. I've been trying to install Due support through the Board Manager, but when I open the Boards Manager, I get :

Error downloading http://downloads.arduino.cc/packages/package_index.json

and when I try to install Due support, I get :

Error downloading http://downloads.arduino.cc/cores/sam-1.6.4.tar.bz2

I understand I may be behind proxies, but in IDE version 1.6.5, that has been removed from the Preferences, so I can't change that. I have tried to allow the IDE past the Windows Firefall, but that has not changed anything.

I have manually downloaded sam-1.6.4.tar.bz2 and extracted the contents to C:\Arduino\arduino-1.6.5\hardware\arduino\sam (I had to manually create the sam folder). With this, I can see the options of Arduino Due Native USB Port and Arduino Due Programming Port when selecting the board, and when I look for it in the Ports, it can recognise the board at the port (eg "COM5 (Arduino Due (Programming Port))" ). When I try to compile anything, I get the error message :

Cannot run program "{runtime.tools.arm-none-eabi-gcc.path}\bin\arm-none-eabi-g++" (in directory "."): CreateProcess error=2, The system cannot find the file specified

Any other idea as to how I can install the Due? Is there an option for a manual installation? The same happens with Libraries Manager (I don't get a connection), so I guess, the same can be applied to that.


texts:
I have 2 Xbee Series 2 modules.
One of it is connected to arduino via an adapter. And Ground 5V, as well as Rx>>Tx and Tx>>Rx.

The xbee is configured AT mode Coordinator.

I want to use the serial monitor in arduino to change the parameters of the xbee, such as DH or DL or PAN ID things like this.

Is there a way for the xbee to display its "OK" response after entering command mode on the serial monitor?


texts: AT command XBee from atmega to disable DIO5 (associated led)

texts:
I community! I need put ATcommand to my XBee from my atmega using a "xbee library" and a function that I have found in internet. I think the ATComand is "ATD50" to change the DIO5 to value "0" (disabled). My intention is to turn off a led connected into DIO5 (digital input/output 5 (associated led)) after X second/minutes of turning on the device (so that it doesn't turn one again after initial check).

This is a part of my code:

#include <XBee.h>
XBee xbee = XBee();
uint8_t atdCmd[] = {'A','T','D','5','0'}; //<---command to put DIO5 to "0" (disabled)
AtCommandRequest atRequest = AtCommandRequest();
AtCommandResponse atResponse = AtCommandResponse();
void setup()
{
delay(30000);
atRequest.setCommand(atdCmd);
xbee.send(atRequest);
}
void loop()
{}

...but it doesn't work!
Thanks guys!


texts: Start/Stop/Reset the melody using buttons

texts:
I have 2 buttons.  Button 1 will start/stop the melody while the button 2 will reset the melody. My melody is "Happy Birthday".

How am I going to use the buttons to start/stop/reset the melody?

Here's the code:

#include "pitches.h"

int melody[] = {
    NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, NOTE_C4, NOTE_B3,
    NOTE_G3,NOTE_G3, NOTE_A3,NOTE_G3, NOTE_D4, NOTE_C4,
    NOTE_G3, NOTE_G3, NOTE_G4,NOTE_E4,NOTE_C4, NOTE_B3, NOTE_A3,
    NOTE_F4, NOTE_F4, NOTE_E4, NOTE_C4, NOTE_D4, NOTE_C4
};

int noteDurations[] = {
    8,8,4,4,4,2,8,8,4,4,4,2,8,8,4,4,4,4,3,8,8,4,4,4,2
};

boolean needtoPlay;

void setup() {
    pinMode(4, OUTPUT);
    pinMode(2, INPUT); //START/STOP
    pinMode(3, INPUT); //PAUSE
}

void loop() {
    for (int thisNote = 0; thisNote < 26; thisNote++) {
        int noteDuration = 1000 / noteDurations[thisNote];
        tone(4, melody[thisNote], noteDuration);
        int pauseBetweenNotes = noteDuration * 1.60;
        delay(pauseBetweenNotes);
        noTone(4);

        if (needToPlay == true) {
        }
    }
}


texts: how can i send get and post request from esp01 using arduino uno

texts:
I am using an esp8266 01 module with the Arduino Uno to establish a communication between the Arduino and my web site. I actually don't know how to send Rest HTTP requests from the Arduino to get data from my web site. I have done research but all I got is codes using nodemcu so I was wondering will the code of nodeMCU work fine on the Arduino using ESP01 and if not then how can I send get and post request from the Arduino using esp01
this the code that I found

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>

const char* ssid = "SERVER NAME";
const char* password = "SERVER PASSWORD";

void setup()
{
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(1000);
    Serial.println("Connecting...");
  }
}

void loop()
{
  if (WiFi.status() == WL_CONNECTED)
  {
    HTTPClient http; //Object of class HTTPClient
    http.begin("http://jsonplaceholder.typicode.com/users/1");
    int httpCode = http.GET();

    if (httpCode > 0)
    {
      const size_t bufferSize = JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(8) + 370;
      DynamicJsonBuffer jsonBuffer(bufferSize);
      JsonObject& root = jsonBuffer.parseObject(http.getString());

      int id = root["id"];
      const char* name = root["name"];
      const char* username = root["username"];
      const char* email = root["email"];

      Serial.print("Name:");
      Serial.println(name);
      Serial.print("Username:");
      Serial.println(username);
      Serial.print("Email:");
      Serial.println(email);
    }
    http.end(); //Close connection
  }
  delay(60000);
}


texts:
I have some basic code that I will soon expand for my project which is a universal remote for air conditioners. I have all of the codes but the problem is 3 of the codes are below 1khz. (500hz). My sketch doesn't allow for anything to go lower and the frequency in the actual code doesn't seem to go that low. 108 is 38khz.
uint16_t fuck[] = {0,108,0,0,347,173,22,22,22,22,22,22,22,65,22,65,22,65,22,22,22,22,22,65,22,65,22,65,22,22,22,22,22,22,22,65,22,65,22,22,22,65,22,22,22,22,22,65,22,22,22,22,22,22,22,65,22,22,22,65,22,65,22,22,22,65,22,65,22,65,22,1527,347,87,22,3692};
static uint16_t sent_array_numbers;
static uint8_t ir_seq_index = 4;
static uint8_t pin_state;

void ir_on()
{
  TCCR1A |= 192;
  pin_state = 1;
}

void ir_off()
{
  TCCR1A &= -193;
  pin_state = 0;
}

void ir_toggle()
{
  if (pin_state)
    ir_off();
  else
    ir_on();
}

void ir_start()
{
  DDRB |= 10;
  ICR1 = 416;
  OCR1A = 104;
  TCCR1A = 2;
  TCCR1B = 24;
  TIMSK1 = 1;
  ir_on();
  TCCR1B |= 1;
}

ISR(TIMER1_OVF_vect) {

  sent_array_numbers++;

  if (sent_array_numbers == fuck[ir_seq_index]) {
    ir_toggle();
    sent_array_numbers = 0;
    ir_seq_index++;

       }
}

void setup() {
  ir_start();
}

void loop() {

}


texts:
I am using arduino mega for my application .  Board works well for a week , from yesterday it  is not programming at all , it shows me some error like timeout . What could be the problem kindly  help me to solve this.

avrdude: Version 6.3, compiled on Dec 16 2016 at 13:33:19
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

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

         Using Port                    : COM20
         Using Programmer              : wiring
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "\\.\COM20": The system cannot find the file specified.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
avrdude: ser_drain(): read error: The handle is invalid.

avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

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

avrdude done.  Thank you.


texts: Arduino original motor shield can not supply enough torque to the motor?

texts:
I am using original Arduino motor shield L298P with Arduino uno.

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

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

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

What might be going wrong?

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

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

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

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

delay(1000);
}


texts: Porting Arduino code to AVR/C++ input not working?

texts:
So. I'm trying to read an input on the Arduino Nano using C++/AVR/Eclipse instead of the regular arduino IDE.
The code below is working in the arduino IDE

void setup() {
  // put your setup code here, to run once:
  pinMode(13, OUTPUT);
  pinMode(5, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(digitalRead(5)){
    digitalWrite(13,1);
  }else{
    digitalWrite(13,0);
  }
}

I'm porting the code to AVR/C++ in Eclipse, regular blinking leds is working... but I can't read inputs for some reason...

#define F_CPU 16000000UL //16MHz
#include <avr/io.h>
#include <util/delay.h>

#define set_bit(Y,bit_x) (Y|=(1<<bit_x))
#define clear_bit(Y,bit_x) (Y&=~(1<<bit_x))
#define isset_bit(Y,bit_x) (Y&(1<<bit_x))
#define toggle_bit(Y,bit_x) (Y^=(1<<bit_x))

int main( ){
    DDRB = 0xFF;//Setting all portB pins to output (D13/PB5 - LED)
    DDRD = 0x00;//Setting all portD pins to input  (D5 /PD5 - INPUT)

    while(1){
        if(isset_bit(PORTD,PD5)){//if input... doesn't work?
            set_bit(PORTB,PB5);//Set output (Tested to be working)
        }else{
            clear_bit(PORTB,PB5);//Clear output
        }
    }
}


texts:
I'm trying to report temperature to a server every minute using the CC3000 and Adafruit's library. It runs between 2-20 hours before the connectTCP() call stops working. Should I run through the CC3000 setup again when that happens, begin() and connectToAP()?

Which leads to a larger question of how to structure the CC3000 calls to recover from events like internet connection loss, wifi router reboot, etc. The examples I've looked at in the Adafruit library don't seem to do any recovery from those situations.

Update: (Added links.) I'm starting to think this might be a power issue. I just found a note on the product page recommending a minimum 1A power supply, and mine is 650mA. 1A power supply on order. I'll see if that helps.

My code is rather involved as it's actually a thermostat, e.g. LCD plus control buttons.


texts: How to use an external clock with the Due timer?

texts: I want to use an external clock signal as an interrupt for the Due timer. How do I do that? I could not find any info on this on the net.


texts: Problem with serial driver for CH340G board

texts:
I bought a USB Nano V3.0 ATmega328 16M 5V Micro-controller CH340G board For Arduino and tried it with Arduino 1.6.6 on my MacBook Pro running OS X 10.11.1

The USB serial could not be seen. I searched on the web and found a few posts about this board, and downloaded http://www.wch.cn/download/CH341SER_MAC_ZIP.html

Most of the instructions were in Chinese, but the driver CH341SER_MAC.ZIP 资料类型：应用资料 资料大小：250KB 资料版本：1.1 更新时间：2013-12-25 seemed to install, but I cannot seem to find any /dev/tty and Arduino can't see any serial ports.

Has anyone had any success with this. (The seller has sold 18000 of these so someone may have got it working.)


texts:
How can I tackle self-diagnosis problem within my Arduino project?
For example, I have a temperature sensor and humidity sensor. How can I know if they work or not on Arduino start or inside the sketch loop?


texts: Arduino Uno - Multiple modules for HDMI switch device

texts:
I have an Arduino Uno device that uses the following modules:

16 PIN LED w/ Backlight
RFID - RC522 (RFID Reader)
HR911105A (LAN Module - HanRun)

These three modules use every digital pin available in the Uno (2-13) and
it works correctly. The problem is that I want to add a relay to this board. I am new to Arduino so I use tutorials and right now I do not fully understand how this works. So I have connected the IN pin of the relay to Uno pin 8 and the NO pin of the relay to Uno pin 13.

The problem is that when I don't use other modules the relay works correctly (using this code).

int relay_pin = 8;
int led_pin = 13;

void setup() {
  pinMode(relay_pin,OUTPUT);
  pinMode(led_pin,OUTPUT);
  digitalWrite(led_pin,HIGH);
}

void loop() {
  digitalWrite(relay_pin,HIGH);
  delay(5000);
  digitalWrite(relay_pin,LOW);
  delay(5000);
}

The remaining ports are 1 and 0, which I assume are TX/RX, and can't be used for relay (am I wrong?).

So obviously I should not be using those pins but I wonder which pins I am allowed to use simultaneously when using two or three modules at the same time.

Does it depend on the modules or are there some instructions?


texts: Arduino Uno doesn't work as Manchester code receiver

texts:
I'm sending some data from ATTINY85 to Arduino UNO using 433Mhz modules. Coding is Manchester using Manchester.h library from here.

Transmitting data works perfectly, 433 receiver gets data alright.

But Arduino UNO does not seem to receive data! Here is the code of the receiver:

/*
  Manchester Receiver example

  In this example receiver will receive one byte of payload and 4 bit sender id per transmission
  message also contains a checksum and receiver can check if the data has been transmitted correctly
  try different speeds using this constants, your maximum possible speed will
  depend on various factors like transmitter type, distance, microcontroller speed, ...
  MAN_300 0
  MAN_600 1
  MAN_1200 2
  MAN_2400 3
  MAN_4800 4
  MAN_9600 5
  MAN_19200 6
  MAN_38400 7
*/
#include <Manchester.h>

#define RX_PIN  4  //pin where your receiver is connected

uint8_t moo = 1;
uint8_t data;
uint8_t id;

void setup() {

//  pinMode( RX_PIN, INPUT );
  man.setupReceive(RX_PIN, MAN_600);
  man.beginReceive();
  Serial.begin(9600);
}

void loop() {
  if (man.receiveComplete()) { //received something
    uint16_t m = man.getMessage();

    Serial.write(m);
    man.beginReceive(); //start listening for next message right after you retrieve the message
  }

}

Transmitter code:

/*
  Manchester Transmitter example

  In this example transmitter will send one byte of data and 4bit sender ID per transmission
  message also contains a checksum and receiver can check if the data has been transmitted correctly
  try different speeds using this constants, your maximum possible speed will
  depend on various factors like transmitter type, distance, microcontroller speed, ...
  MAN_300 0
  MAN_600 1
  MAN_1200 2
  MAN_2400 3
  MAN_4800 4
  MAN_9600 5
  MAN_19200 6
  MAN_38400 7
*/
#include <Manchester.h>

#define TX_PIN  4  //pin where your transmitter is connected
#define SENDER_ID 5

uint8_t transmit_data = 0;

void setup() {
  man.setupTransmit(TX_PIN, MAN_600);
}

void loop() {
  //SENDER_ID can be ID of the sender if you have multiple transmitters so receiver knows who sent it
  //OR it can be receiver ID if you have multiple receivers so receiver knows it's for him
  //OR it can by just any arbitrary 4 bit number
  man.transmit(man.encodeMessage(SENDER_ID, transmit_data));
  transmit_data++;
  delay(200);
}

Anyone got idea what's the problem?


texts: Multiple node communication using NRF24L01

texts: Code for detecting data available at which pipe when using multiple pipe for communication??


texts: How can I make my custom board use the programmer selected in "Tools->Programmer" when the Upload button is pushed?

texts:
I've created a custom board that can be programmed using any one of several programmers defined in programmers.txt. I would like the user to be able to choose which programmer to use via the "Tools->Programmer" menu options.

I tried using {protocol} and {upload.protocol} in platform.txt to pass the programmer to the upload tool, but neither seem to be defined when the Upload button is used to initiate the upload (they are defined if Upload using programmer is selected from the menu).


texts: Can a Arduino Uno handle all these components?

texts:
Its my first project with an Arduino, so please bear with the dumb questions.

For this project of mine, I need an Ultrasonic Sensor, a Gyroscope, a Buzzer, three push buttons and an 16x2 LCD.

Can I connect all these components at once to an Arduino Uno? I mean will I run out of pins or not? Should I go for a Mega 2560 (will have to buy one though).

Edit: a GSM sim800 as well lol


texts:
I want to avoid global variables when using my own classes in Arduino. Here is a example.

void setup(){
/* setup here */
  classA objectA;
}

void loop(){
  objectA.someMethod();
}

I know that my compiler will complain about it (out of scope, etc) but is it possible to do that or just forget it and use globally?

Thanks in advance!


texts:
My current project involves embedding an MPU6050 accelerometer into straps, one of which goes below the knee, the other above the knee.

I need to fit the sensor into the strap and currently i have 6-core multi-threaded wire soldered directly into the board. This doesn't facilitate the greatest of long term stability, as too much strain and the wires will just pull out and break.

What I am wondering is if it is OK to:

cover the wire side of the board in glue from a hot glue gun?
                 Would this have any possible conductivity issues or risk damaging the wires or board itself?
If it is OK to use the hot glue, would it be possible to cover the entire MPU6050 in the glue without compromising performance. This would leave me with a really solid sensor for embedding if so!

Any answers to the above questions would be greatly appreciated and I would be extremely grateful for any alternative options as well. I would like to keep the wires soldered into the board as it is extremely tidy and makes for easier embedding than if I were to use another connector.


texts:
I have connected the LCD by the 3 wire method using the LiquidCrystal595 library+74HC595 register shift; sometimes "hello world" is displayed but other times the LCD displays weird characters.
How to solve this problem?


texts: Send and Receive with ESP8266 and arduino

texts: Hi i would like to implement a sensor and control system for my home. Basically, i would like to send and receive data to my arduino uno using esp8266. I am able program the esp8266 using at commands to send http request to my server. How can i make my server send commands to my arduino uno using esp8266?


texts: Can someone check my code? My Arduino isn't doing a consistent count cycle

texts:
I'm wondering if someone could have a look at my code and let me know if there's something wrong with it. I had the code done for me a while back and did a quick test and it seemed to work. I have now built a pneumatic machine for it to work on, and it's doing some strange things.

The first relay turns on and off a pneumatic solenoid, this is connected to a small pneumatic cylinder, it moves in and out. This cylinder causes a pneumatic feeder to activate and move back and forth also.

The feeder has a proximity sensor attached which lights up when the feeder is in its resting position.

The solenoid turns on for approx half a second and then back off again, this pushes the small cylinder out then back in. This sends the feeder forward, it then turns around and comes back toward its resting position.
The Arduino waits for the signal from the proximity sensor to tell it that the feeder is back in its resting position before doing it again.

It then repeats this sub cycle about 20 times.

After 20 sub cycles, the Arduino turns on the second relay for about a second, before turning it back off again.

It then does this whole complete cycle 20 times before stopping.

There's a momentary switch as well, which when pushed, is supposed to restart everything again.

It almost works, the closest i have had is where it was doing the cycles but counting them wrong. i changed the subcycle to 16 instead of 20 and it would count somewhere between 10 and 16. it seems to count different each time.

I just bought a new board and tried again, but now it counts to about five subcycles and then jumps the gun and doesn't wait for the signal from the proximity sensor before doing the next sub cycle. So once again the count ends up wrong.

Any ideas what I could try?

int Relay_1 = 10;           //first Relay
int Relay_2 = 11;           //second Relay
int Prox_Input = 12;        //input signal from proximity sensor
int Switch_Input = 13;      //the switch

int Cycle_Number = 20;      //number of repeating number of "complete" cycle
int Sub_Cycle_Number = 20;  //number of repeating number of "sub" cycle
int Delay_Cycle = 1000;     //delay of the "Complete" Cycle in milleseconds
int Delay_Sub_Cycle = 500;  //delay of the "Sub" Cycle  in milliseconds

bool Button_Pushed = true ; //the state required for the button
int i, j;

void setup() {
  /*configurate the output relays to be begin "low"*/
  pinMode(Relay_1 , OUTPUT);
  digitalWrite(Relay_1, LOW);

  pinMode(Relay_2 , OUTPUT);
  digitalWrite(Relay_2 , LOW);
  /*===========================================================*/
  /*configurate the input switch and sensor*/
  pinMode(Prox_Input , INPUT);
  pinMode(Switch_Input , INPUT_PULLUP);
  /*===========================================================*/
  /*configurate Serial port if you want it*/
  Serial.begin(9600);
  /*===========================================================*/
}

void loop() {
  if (Check_Button() == Button_Pushed) { //check the button
    for (i = 1 ; i <= Cycle_Number ; i++) { //the loop of the "complete" Cycle
      for (j = 1 ; j <= Sub_Cycle_Number ; j++) { //the loop of the "sub" Cycle
        digitalWrite(Relay_1 , HIGH);
        delay(Delay_Sub_Cycle);
        digitalWrite(Relay_1 , LOW);
        while (digitalRead(Prox_Input) == HIGH) {} // waiting the sensor signal
      }
      digitalWrite(Relay_2 , HIGH);
      delay(Delay_Sub_Cycle);
      digitalWrite(Relay_2 , LOW);
      delay(Delay_Cycle);
    }
  }
}

bool Check_Button()  {
  int Reading_1;
  int Reading_2;

  Reading_1 = digitalRead(Switch_Input);
  delay(20);
  Reading_2 = digitalRead(Switch_Input);
  if ((Reading_1 == 1) && (Reading_2 == 1))
    return true;
  else
    return false;
}


texts: Get value from a website using Yún and a RPi

texts:
I have a project that requires opening a door remotely. I'm using an arduino Yún and a raspberry pi.
 I have a switch connected to the RPI and i'm sending it's value to a web server. How can I get the value from the website to the arduino, so that it can process it and see if an order to open the door is issued?

Thanks for any help :)


texts: Increase IR transmitter directivity and range

texts:
I am working on a project to control different devices with arduino and IR LED so I am testing with this circuit:

So, everything is working fine but I want to increase range of my transmitter. For now its barely giving response at 1 meter distance. I want to increase this to at least 5 meters. I tried to increase receiver sensitivity by giving 5V to TSOP, when I do this the range is satisfactory but the directivity is too much its even responding when I point IR LED in opposite direction(inside a room, maybe the radiaton is bouncing off walls - this is not happening with 3.3V). I Know the transmitter range can be increased by increasing the current flowing through LED like this (please correct me if I am wrong):
The problem is with directivity of emitter, I do not want all the devices in my room to turn on when I try to turn on my TV. The devices are placed  up to 1 meter apart and the transmitting range should be at least 5 meters.

Also it would be helpful if someone clarifies which part is actually sensitive (the part which looks like LED or the flat backside part - image below) for TSOP i.e. which part receives the pulses, so that I can cover it with tape (so that it receives signal from only one direction) if nothing else works.

Any help is appreciated, thank you.


texts: How do i get stored Midi to Play back without the notes sounding sustained?

texts:
How can i get my stored midi notes to play back without sounding sustained like in this video : https://youtu.be/zc1zbwheyE0?t=2m30s. Here is some of my code:

// Callback function to for recording note played is called upon reception of a NoteOn.
void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {

if ((currentState != STATE_R) || (noteIndex >= MAX_NOTE))
      return;

  // Record the note
  noteList[noteIndex].channel = channel;
  noteList[noteIndex].pitch = pitch;
  noteList[noteIndex].velocity = velocity;
  noteList[noteIndex].deltaT = millis() - lastNoteTime;

  lastNoteTime = millis();
  noteIndex++;

 }

 void StateMachine(void)
{
  static uint16_t  nextNote;

MIDI.read();   // keep this going as fast as possible and empty buffer all the time

  switch (currentState)
  {
    case STATE_I2P:    // Set up for playback

      nextNote = 0;
      lastNoteTime = millis();
      SwitchState(STATE_P);
      break;

    case STATE_P:      // Play the notes back
   lcd.clear();
 lcd.setCursor(5,0);
  lcd.print("Playing Recorded Song");
  if (nextNote >= noteIndex) SwitchState(STATE_P2I);  // we are done

       if ((millis() - lastNoteTime) >= noteList[nextNote].deltaT)
       {
         MIDI.sendNoteOn(noteList[nextNote].pitch, noteList[nextNote].velocity, 1); //noteList[nextNote].channel);  // Send the note
        noteOn(0x90,noteList[nextNote].pitch,100);
         nextNote++;
         lastNoteTime = millis();
       }
      break;
   }


texts:
can someone please point me at some code snippets to detect when the GPS is stationary. I am currently using tinyGPS library and it is working fine, but my data-logger has thousands of stationary details I'd like to not bother logging. Currently I am using this,

uint8_t speedZero() {
uint8_t spd = gps.speed.mph();
  if (spd < 5) {
    return 0;
  } else {
    return spd;
  }
}

But it is too granular at slow speeds, but the NEO-6M drifts a lot and 5mph standing still is not uncommon.

I have tried comparing Last Lat/Lon but not having any success as this Math is waaaay out of my skill-zone.


texts: Reading FAN tachometer/RPM on 4 wire fan using arduino

texts:
I am following the wiring and code at https://playground.arduino.cc/Main/ReadingRPM but using pin 9 to read the speed instead of pin 2 and I have added a 10K pull up resistor between pin 9 and +5V as well; I dont see any interrupts firing even though the fan is running;

The fan is a standard intel cpu fan with 4 wires(black, yellow, green, blue) and the green wire is the sense/tach wire and I have connected it to pin 9 as well;

Need some help or expert advise; I am not sure if the approach works fine or not;


texts: Significance of the numbers used in the manual

texts:
i just bought the starter kit and am currently working my way through the examples in the book when i came across some numbers used in the manual that seems a little too specific.

For example, in project #3,the love-o-meter, i had to divide the sensor value by 1024.0, and the explanation for it was never given in the manual.

Furthermore, in project #4(which i'm currently at), the book states that i have to convert sensor readings from 0 - 1023, to a value between 0 to 255.Is the number 1024/1023 simply an arbitrary number/limit set by the sensor's manufacturers? Also, is they any significance or reason that analogueWrite only accepts positive values up to 255?

Thanks!


texts: SimpleSDaudio giving a lot of static from speaker

texts:
I'm using SimpleSDaudio (http://www.hackerspace-ffm.de/wiki/index.php?title=SimpleSDAudio) to play wav files. The connections are as follows:

MISO pin 12

SCK pin 13

SS pin 4

MOSI pin 11

Speaker pin 9

/*
 Simple SD Audio bare minimum example, plays file EXAMPLE.AFM from root folder of SD card.

 This example shows how to use the SimpleSDAudio library for audio playback.
 You need:
 - An Arduino with ATmega368 or better
 - An SD-Card connected to Arduinos SPI port (many shields will do)
   -> copy EXAMPLE.AFM on freshly formated SD card into root folder
 - A passive loudspeaker and resistor or better: active speakers (then stereo output will be possible)

 Audio signal output is at the following pin:
 - Arduino with ATmega328       (many non-mega Arduinos): Pin 9
 - Arduino with ATmega1280/2560 (many mega Arduinos)    : Pin 44

 Using passive speaker:
    Audio-Pin --- -[100 Ohm resistor]- ---- Speaker ---- GND

 Using amplifier / active speaker / line-in etc.:
    Audio-Pin --||--------------[10k resistor]----+----[1k resistor]---- GND
              100nF capacitor                   to amp

 See SimpleSDAudio.h or our website for more information:
 http://www.hackerspace-ffm.de/wiki/index.php?title=SimpleSDAudio

 created  20 Jan 2013 by Lutz Lisseck
 */
#include <SimpleSDAudio.h>

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

  // Using F("...") to avoid wasting RAM
  Serial.print(F("\nInitializing SD card..."));

  // If your SD card CS-Pin is not at Pin 4, enable and adapt the following line:
  // SdPlay.setSDCSPin(10);

  if (!SdPlay.init(SSDA_MODE_FULLRATE | SSDA_MODE_MONO | SSDA_MODE_AUTOWORKER)) {
    Serial.println(F("initialization failed. Things to check:"));
    Serial.println(F("* is a card is inserted?"));
    Serial.println(F("* Is your wiring correct?"));
    Serial.println(F("* maybe you need to change the chipSelect pin to match your shield or module?"));
    Serial.print(F("Error code: "));
    Serial.println(SdPlay.getLastError());
    while(1);
  } else {
   Serial.println(F("Wiring is correct and a card is present."));
  }

  Serial.print(F("Looking for on.wav... "));
  if(!SdPlay.setFile("hi.wav")) {
    Serial.println(F(" not found on card! Error code: "));
    Serial.println(SdPlay.getLastError());
    while(1);
  } else {
   Serial.println(F("found."));
  }

  Serial.print(F("Playing... "));
  SdPlay.play();
  while(!SdPlay.isStopped()) {
    ;   // no worker needed anymore :-)
  }
  Serial.println(F("done."));
  SdPlay.deInit();
}

void loop(void) {

}

The problem is when playing the wav files. It plays with a lot of static. I've tried adding a 1k resistor between the speaker and gnd but that just lowered the overall volume. I resampled the wav files in itunes to 32khz, 8bit, mono. If I lower to 16khz then the audio volume becomes very low and the song just plays extremely fast. Here is a google drive link to one of the sounds:
https://drive.google.com/file/d/0B3yAl4G-mcC4dlppN3dtczJvT1k/view?usp=sharing

I really need help. I'm not sure what to do!


texts:
I have a String content="" and if I put an HTTP request like this:

client.println("GET /api/actions?parking_id=39 HTTP/1.1");
client.println("Host: ramp-rampcontrol.rhcloud.com");
client.println("Connection: close");
client.println();

the output I get is:

 [{"action_id":35,"action_type":"up","parking_id":39,"user_id":17,"ramp":"exit","created_at":"2015-07-10 18:02:40","updated_at":"2015-07-10 18:02:40"},{"action_id":41,"action_type":"up","parking_id":39,"user_id":17,"ramp":"entry","created_at":"2015-08-16 20:50:14","updated_at":"2015-08-16 20:50:14"},{"action_id":42,"action_type":"down","parking_id":39,"user_id":17,"ramp":"entry","created_at":"2015-08-16 20:50:21","updated_at":"2015-08-16 20:50:21"},{"action_id":43,"action_type":"down","parking_id":39,"user_id":17,"ramp":"exit","created_at":"2015-08-16 20:50:22","updated_at":"2015-08-16 20:50:22"}]

The little parser I created is this:

while(client.available()) {
 char c = client.read();
    if(c == '{'){
      begin1 = true;
    }

  if (begin1) {
    content += c;
   }

  if (c == '}') {
      break;
    }
 }

Is it possible to store only the first action in JSON output, because the actions are updated, and if the number of chars extends 256 than I get errors while working with the String content?


texts: Will a simple RC filter work with my mechanical rotary encoder, or do I need a Schmitt trigger?

texts:
I bought some incremental rotary encoders online  https://www.bourns.com/docs/Product-Datasheets/PEC12R.pdf

The spec sheet for those suggests a filter circuit for the outputs of the encoder that looks like this:

Adding that filter reduces, but doesn't eliminate, spurious signals from the encoder. I wanted to avoid adding Schmitt triggers or other solid state components since I don't have a lot of room left on my proto board for an IC, but I'm beginning to think I will have to add something with hysteresis since any filter that reduces jitter will also slow the rise time/fall time for the output of the encoder and keep it in the "gray area" between LOW and HIGH for a digital signal for too long.

Is there a way to wire these encoders and/or software that lets you read from them with simple passive filtering and/or software rather than adding something like a latch or Schmitt trigger for debouncing?


texts: Connect to more than one Arduino with Adobe AIR

texts:
I am using the arduinconnector ANE to connect to an arduino baord in an AIR application. https://code.google.com/p/as3-arduino-connector/

Can anyone tell me if its possible to connect to more than 1 board, simply by instantiating additional instances of the ANE and passing in unique port #'s?

Or is there some reason why this isn't possible and a unique AIR application is required for every arduino you connect to?


texts: How can the Arduino check if it is connected to a PC and the PC is on?

texts:
I have been searching around the Internet to find if there is a way to check whether an Arduino is connected to a PC or not.

For example: if my PC is turned on, the Arduino will listen to any serial commands it receives, BUT if my PC is turned off, the Arduino will receive some random characters.

How can the Arduino check if it is connected to PC and the PC is on?


texts: How to drive RGB LED fading alongside MAX7219s

texts:
Merry XMAS

I have a pro mini which drives 2 RGB LED strips on its 6 PWM pins, via 6 2N7000 N-channel MOSFETs. Alongside these, I have  4 x MAX7219 modules in series controlled via SPI. Both work perfectly, but not concurrently - yet. I need to do sleek PWM on the RGB strips whilst outputting scrolling text on the MAX7219s.
The functions for the MAX7219 display take some time to complete for each blob of text.

I added a udelay() function (works like delay(), but just uses delayMicroseconds instead) so I could use interrupts/timers.

I am now interested in the best practice for doing that - I have no experience with interrupts, and would rather not use something lile FreeRTOS for this.

Desired functionality:
1) Drive 2 RGB LED strips on 6 PWM pins, smoothly.
2) While at the same time outputting arbitrary text/foo on the MAX7219s on SPI.

I have this snippet for smoother RGB fading ( http://forum.arduino.cc/index.php?topic=12004.0 ) and would also like to know what variables periode, displace denote, and if this method has merit.

void loop()
{
 time = millis();
 value = 128+127*cos(2*PI/periode*time);
 value2 = 128+127*cos(2*PI/periode*(displace-time));
 analogWrite(ledpin, value);           // sets the value (range from 0 to 255)
 analogWrite(ledpin2, value2);           // sets the value (range from 0 to 255)
}

@Majenko et al?

Cluebats at the ready - any advice would be appreciated!


texts: How do I display serial monitor on LCD keypad shield?

texts:
I want to be able to display what I am seeing on the serial monitor onto the LCD keypad shield I have connected to my Arduino UNO. Can someone possibly write the the code ontop of this for me?
I'm very new to coding so I apologies if it's hard for anyone to understand what i'm asking for.

int ledPin = 13; // LED is attached to digital pin 13
int x = 0; // variable to be updated by the interrupt

//variables to keep track of the timing of recent interrupts
unsigned long button_time = 0;
unsigned long last_button_time = 0;

void setup() {
  //enable interrupt 0 which uses pin 2
  //jump to the increment function on falling edge
  attachInterrupt(0, increment, FALLING);
  Serial.begin(9600);  //turn on serial communication
}

void loop() {
  digitalWrite(ledPin, LOW);
  delay(500); //pretend to be doing something useful
  Serial.println(x, DEC); //print x to serial monitor
}

// Interrupt service routine for interrupt 0
void increment() {
  button_time = millis();
  //check to see if increment() was called in the last 250 milliseconds
  if (button_time - last_button_time > 250)
  {
    x++;
    digitalWrite(ledPin, HIGH);
    last_button_time = button_time;
  }
}


texts: Playing a pcm file through a speaker with arduino

texts:
I'm trying to play an audio file through a speaker with arduino.
However, I do not want to use pre-constructed libraries such as the tmrpcm library.

I was instructed to perhaps even recreate the tmrpcm library, and my process so far is that I managed to extract the data chunk from the wav file in integers, and I also managed to turn the wav file into a pcm file.

I am currently studying http://playground.arduino.cc/Code/PCMAudio this link in order to gain more insight about how I might play the pcm file with the speaker. However, I'm stuck with the general concept of the code. In fact, I'm confused with the general concept of playing the pcm file through the speaker.

In my understanding, playing a music through the speaker works by outputting series of voltages to the speaker, so that the current in accordance with the magnetic field creates an outward force onto the voice coil with a certain frequency that creates the sound.

So my question is, what does the data in the pcm file actually mean? The integers cannot be frequencies, and by graphing it I can see that they are amplitudes in a waveform, but what kind of input they are continues to elude me.

So summing up my questions,

What is the theoretical aspect behind the link :http://playground.arduino.cc/Code/PCMAudio
What does the data in a pcm file (or even a wav file) actually represent?

Thank you so much.


texts: serial.write() five sensors and Processing

texts:
To all of this, hope to formulate the question right.

In my project I have 5 sensors connected to Arduino, which I want to interpret via Seria.write() --> Processing.

Arduino:

firstSens = 100 + (155 * digitalRead(8));
secondSens = analogRead(A1)/4;
thirdSens = analogRead(A2)/4;
fourthSens = humData;
fifthSens = tempData;
int sensData[6] = {firstSens, secondSens, thirdSens, fourthSens, fifthSens};

int i;
for (i = 0; i < 5; i = i + 1) {
  Serial.write(sensData[i]);
}

Processing:

serialInArray[serialCount] = inByte;
    serialCount++;

if (serialCount > 4 ) {
  firstSens = serialInArray[0];
  secondSens = serialInArray[1];
  thirdSens = serialInArray[2];
  fourthSens = serialInArray[3];
  fifthSens = serialInArray[4];

  // print the values (for debugging purposes only):
  println(firstSens + "\t" + secondSens + "\t" + thirdSens + "\t" + fourthSens + "\t" + fifthSens);

  // Send a capital A to request new sensor readings:
  myPort.write('A');
  // Reset serialCount:
  serialCount = 0;

My problem is that sensors find their place in Processing's array randomly, so for example arduino's firstSens could be Processing's secondSens or fifthSens

Why is this happening and how can I control it?


texts:
I'm trying to send a signal from Raspberry Pi GPIO to Arduino. I made a sketch that basically reads the state of the digital read, but the reading are very unstable. I understand that there is a floated voltage and the obvious solution is to configure the pullup resistor and connect the input to ground, but my goal is to read the incoming signal.
I'm using Arduino Mega 2560 and Raspberry Pi 2B.

I hope this info is enough!


texts: Why would uninitialized SD-card module without card disable CAN-Bus shield?

texts:
(I am able to successfully initialize CAN-Bus shield and SD-card module w/ card in it.)

Now I have removed all code related to the SD-card module, yet I left the module (without the card in it) physically connected. This results in the CAN-Bus shield initialization failing.
When I insert the card into the SD-card module the CAN-Bus shield initializes successfully. (I am still not doing SD-card module initialization.)

Of course, I can just disconnect the SD-card module or leave the card in it... But I am trying to understand this black magic.

I have connected the SD-card module CS to pin 8, the CAN-Bus shield clone CS is connected to pin 10. I tried to set the SD-card module CS pin to OUTPUT and to HIGH. That had no effect.

the CAN-Bus shield + schematics: http://www.elecfreaks.com/estore/can-bus-shield.html [Resource -> Schematics]
the SD-card module: https://ebay.com/itm/161366316226?_trksid=p2057872.m2749.l2649


texts:
I am using a DHT11 sensor attached to a NodeMCU ESP8266 to have a web server reporting the local humidity and temperature values. I don't have a resistor attached in the circuit, the DHT11 is directly connected to the NodeMCU board. Till yesterday, the setup was giving me correct values, but from today morning, I am getting all nulls from the sensor. Does this mean that the sensor is dead? Should I have had a resistor attached to the circuit to prevent this, or does that not make any difference?

EDIT:

Please consider my question before negative voting me. I considered this question:

Problem with a DHT11 Temperature & Humidity sensor

I have followed the circuit diagram as given in the following page:

https://www.electronicwings.com/nodemcu/dht11-sensor-interfacing-with-nodemcu

It's just that I am using a NodeMCU istead of an Arduino. Does that make my question unworthy of posting here? The problem is similar.


texts:
If UNO is supplied with 9VDC to Power Jack.
Will it supply power to USB connector?


texts: Nodemcu stops sending the messages to the API

texts:
Here is my code which sends some data to the firebase cloud functions. The code works well and the nodemcu sends the data to the cloud for about half an hour and then stops sending the messages.

#include <OneWire.h>
#include <DallasTemperature.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>

#define ONE_WIRE_BUS 5

// Use WiFiClientSecure class to create TLS connection
WiFiClientSecure client;

OneWire oneWire(ONE_WIRE_BUS);

DallasTemperature sensors(&oneWire);
String data="";
const char* ssid = "***************";
const char* password = "**************";

const char* host = "**************************";
const int httpsPort = 443;

String url = "/getData";
float Celcius=0;
float Fahrenheit=0;
int sensor_light;
int sensor_temp;
int sensor_moist;
void setup() {
ESP.wdtDisable();
pinMode(16,OUTPUT);//moist
pinMode(0,OUTPUT);//light
Serial.begin(115200);  //Serial connection
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

Serial.print("connecting to ");
Serial.println(host);
if (!client.connect(host, httpsPort)) {
Serial.println("connection failed");
return;
}
ESP.wdtEnable(WDTO_8S);
}
void loop()
{
 client.connect(host, httpsPort);
 int l,m,t;
 data=" ";
 l=get_light();
 t=get_temp();
 m=get_moist();
 if(WiFi.status()== WL_CONNECTED){
    data+="{";
    data+="\"";
    data+="Node-Id";
    data+="\"";
    data+=":";
    data+=1;
    data+=",";
    data+="\"";
    data+="light";
    data+="\"";
    data+=":";
    data+=l;
    data+=",";
    data+="\"";
    data+="temperature";
    data+="\"";
    data+=":";
    data+=t;
    data+=",";
    data+="\"";
    data+="humidity";
    data+="\"";
    data+=":";
    data+=m;
    data+=",";
    data+="\"";
    data+="Latitude";
    data+="\"";
    data+=":";
    data+=29.3589362;
    data+=",";
    data+="\"";
    data+="Longitude";
    data+="\"";
    data+=":";
    data+=79.5506528;
    data+="} ";
    Serial.println(data);
    client.print(String("POST ") + url + " HTTP/1.1\r\n" +
           "Host: " + host + "\r\n" +
           "Connection: close\r\n"+
           "Content-Length: " + data.length()+ "\r\n" +
           "Content-Type: application/json;charset=UTF-8\r\n\r\n"+
            data +"\r\n");
    //  Serial.println("Sent");
    String line = client.readStringUntil('\n');
    Serial.println(line);
    while(!client.connected())
        { client.stop();
          ESP.wdtFeed();
         }
     }
    delay(4000);
    }

    int get_light()
    {
    digitalWrite(0, HIGH);
    sensor_light=0;
    sensor_light = analogRead(A0);
    digitalWrite(0, LOW);
    delay(2000);
    return sensor_light;
    }
    int get_temp()
    {
    int  sum=0,i;
    for(i=0;i<10;i++)
      {
    sensors.requestTemperatures();
    Celcius=sensors.getTempCByIndex(0);
    delay(250);
    sum+=Celcius;
    }
    Celcius=sum/20;
    delay(2000);
    return Celcius;
    }

    int get_moist()
    {
     digitalWrite(16, HIGH);
    sensor_moist=0;
    sensor_moist = analogRead(A0);
    digitalWrite(16, LOW);
    delay(2000);
    return sensor_moist;
    }

If I do not use ESP.wdtFeed() and other similar functions then I am getting Soft wdt reset error. I am using the laptop to power it. Any help?


texts: Free touch big electrodes (arduino zero)

texts:
I want to try making big electrodes 20cm*1 cm
but i got an effect i dont understand.
In the picture red and blue are the diffrent electrodes
at first touch the blue  one and it rises.
then i touched the red  one and it rises.
when i touch both electrodes both signals dropps ??
when itouch both with gloves both rise ??

i think its not allowed to touch the pure cooper

Also i would like to know whats the output from the mesure funktion of the  free touch libary  (physical dimension ,like time or voltage??)

#include "Adafruit_FreeTouch.h"

Adafruit_FreeTouch qt_2 = Adafruit_FreeTouch(A1, OVERSAMPLE_4, RESISTOR_50K, FREQ_MODE_NONE);
Adafruit_FreeTouch qt_3 = Adafruit_FreeTouch(A2, OVERSAMPLE_4, RESISTOR_50K, FREQ_MODE_NONE);

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

  while (!Serial);
  Serial.println("FreeTouch test");
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);

  if (! qt_2.begin())
    Serial.println("Failed to begin qt on pin A1");
  if (! qt_3.begin())
    Serial.println("Failed to begin qt on pin A2");

}

void loop() {
  int counter,result2,result3, result = 0;

  counter = millis();
  result = qt_2.measure();
  result2=result;

  counter = millis();
  result = qt_3.measure();
  result3=result;
    Serial.print(result2);
    Serial.print(" ");
    Serial.println(result3);
  delay(200);
}

the problem was that i touch de the electrodes on the copperside instead for the rearside


texts: Wireless Sensor communication with 100Hz rate

texts: I'm doing my project on haptic feedback systems. I need a 56bits of data transmitted over wirelessly to a computer to process and send the output to another arduino. I tried ESP8266 using TCP/IP protocol. But it is very slow. Are there any faster modules to do the above task with 100hz speed?


texts: Do I have to use an external power supply when connecting an ultrasonic sensor to Arduino?

texts: This might be a very stupid question but please bear with me. So I am using an HC-SR04 Ultrasonic sensor model (5 V) and I want to connect it to Arduino Uno. Do I have to use an external power supply for the ultrasonic sensor (just like with the motors) in order to connect it to the Arduino? Or can I just use the 5 V pin?


texts: Is it possible to modify the animal tags (EM4305) with any module that works with Arduino? 134,2Khz

texts: i have a lot of tags (Animal tags rounded yellow) EM4305, this have 15 spaces of memory and i need change ID writed, currently i'm using this module but it did not can possible write on tag, exist a similar function to Write() from EEPROM, i see that already exist external writers to EM4305, but, is only external?


texts: serially parse integer after serially read

texts:
I want to write below code but I don't know where I doing wrong, so please help me solve this issue.
Serially read some text like number then I want to serially parse integer value into some variable and then my next task is if I wrote as text then serially read string and should save in some other variable...
char c;
String s;
long num1=0;
long num2=0;
void setup()
{
  Serial.begin(9600);
  Serial.println("Let's start: ");
}
void loop()
{
  if(Serial.available()>0)
  {
    delay(5);
    c = Serial.read();
    s += c;
  }
  if(s.length()>0)
  {
    if(s=="n")
    {
        if(num1==0)
        {
        Serial.println("write number: "); //serially print
        num1=Serial.parseInt(); // not serially print
        if(num1>0)
        Serial.print(num1);
        }
        if(num1>0)
        {
        Serial.println("write second number: ");
        num2=Serial.parseInt();
        if(num2>0)
        Serial.print(num2);
        }
    }
    s="";
  }
}


texts: how can i fix the error ? stk500v2_getsync(): timeout communicating with programmer

texts:
I bought this Chinese Arduino Mega 2560 16AU.

This was the first time to deal with Arduino boards. When I try to upload a sketch I always get this error:

stk500v2_getsync(): timeout communicating with programmer

I successfully burnt a bootloader to it using an Arduino uno,
but the same error is there.

Finally I discovered the the loop test is not working, and only the LX LED flashes once  when I enter a letter in the serial monitor.


texts: Do software SPI read from a register using shiftin()

texts:
How to read from a register using software SPI, presumably shiftin()?

It works using the builtin SPI library + hardware SPI.

I seem to be able to write but not read using manual shiftin()/shiftout(). I need to do this because I need a version of this to work on a device that doesn't have hardware SPI. I always read out 0x00000000 using shiftin() as below, but the SPI hardware/library works as expected.

(yes, I've double checked the pin numbers). LIS_MISO_PIN = 12.

  // this works (write):
  SPI.transfer(WriteAddr);
  SPI.transfer(Data);

  // this works (write):
  shiftOut(LIS_MOSI_PIN, LIS_SCK_PIN, MSBFIRST, WriteAddr);
  shiftOut(LIS_MOSI_PIN, LIS_SCK_PIN, MSBFIRST, Data);

  // this works (read):
  SPI.transfer(Reg | 0x80);
  *input = SPI.transfer(0x00);

  // does NOT work, as well as various permutations:
  shiftOut(LIS_MOSI_PIN, LIS_SCK_PIN, MSBFIRST, Reg | 0x80);
  *input = shiftIn(LIS_MISO_PIN, LIS_SCK_PIN, MSBFIRST);


texts:
I've been trying to run the following esp32 LED PWM code to change the LED's brightness, and show the current PWM duty on the webpage, but the PWM values on the webpage won't change until I hit the submit button twice.

#include <Arduino.h>
#include <WiFi.h>
#include <WebServer.h>
WebServer ser(80);
int s=0;
String k;

String iso()
{
  k="
LED PWM<FORM action=\"/\" method=\"post\"><input type=\"text\" name=\"duty\">
 <input type=\"submit\" value=\"Submit\">Cureent Duty=";
  k=k+s;
  k=k+"
";

  return k;
}

void root()
{
  iso();
  ser.send(200, "text/html", iso());

  if (ser.hasArg("duty"))
  {
      iso();
      s=ser.arg("duty").toInt();
      ledcWrite(4, s);
      iso();
      ser.send(200, "text/html", iso());
  }
}

void setup() {
  Serial.begin(9600);
  ledcAttachPin(33, 4);
  ledcSetup(4, 5000, 8);
  WiFi.begin("ssid", "pass");
  Serial.print("\nConnecting To WiFi");
  while (WiFi.status()!=WL_CONNECTED)
  {

    Serial.printf("\n.");
  }
  Serial.print("\nConnected");

  ser.on("/", root);
  ser.begin(80);
}

void loop() {
  ser.handleClient();
}

Here's a GIF addressing the issue


texts: Resuming Serial Connection after sleep on Arduino M0

texts:
For debugging purposes I want my serial connection to resume after sleep.  After running LowPower.sleep() from the <ArduinoLowPower.h> library, I don't get any new serial messages in the serial monitor.
Several factors seem to be at play (which I've listed at the bottom) and I've developed a partial solution but it's not great because it requires some long artificial delays of about 1 second after each sleep to resume the serial.  So to recap, my question is how I can get serial to work after sleeping the microcontroller without having to insert long delays.
For background, I am using an Adafruit Feather M0, which I think actually uses SerialUSB and automatically converts serial commands to that according to the guide, but I am not sure what any of that means.
Here's some stuff I looked into:

COM Port: One factor is that the Arduino disconnects from the my Windows 10 computer at sleep and reconnects when it wakes up sometimes on a different COM port.  Using the program Tera Term instead of the Arduino IDE Serial Monitor seems to keep it on the same COM port.

Serial Flush and End: As notes in my code example, both of these commands seem necessary before sleeping or else I won't receive new messages after sleep.

Delay: Seems that the arduino can send messages right after waking up that Tera Term wont see.  I have to put a delay of 1 full second after waking up or else I won't see the messages.

Here's some code I have tried.
#include <ArduinoLowPower.h>

void setup() {
  Serial.begin(115200);
  while(!Serial){delay(10);}
  Serial.println("start");
}

void loop() {

  Serial.println("");
  Serial.println("sleep");
  Serial.flush();  //if this line is commented out, only one cycle of "sleep" will show
  Serial.end();   //if this line is commented out, only one cycle of "sleep" will show
  //delay(2000);  //doesn't seem to fix anything so commented out
  LowPower.sleep(2000);
  delay(1000);  //at 750 misses some "awake" messages
  //Serial.begin(115200);  //this line doesn't appear to fix anything so commented out
  Serial.println("awake");

Output:
start

sleep
awake

sleep
awake

sleep
awake


texts:
I'm building a vehicle tracker with Arduino shield with Waveshare SIM 808. I am communicating with the Arduino via AT commands, and came across the following problem: The method "leserial ()" returns me the result of the command missing characters

Response
+CGNSINF: 1,1,20161101222934.000,-23.285230,-51.20

Expected response
+CGNSINF: 1,1,20161101223215.000,-23.285222,-51.204778,623.000,0.02,142.3,1,,1.2,2.5,2.2,,8,7,,,38,,

Code:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); //RX, TX

String inputString = "";
char inChar;

const int powerkey =  5;
const int statuspin = 6;

void setup() {
  Serial.begin(9600);
  mySerial.begin(9600);
  pinMode(powerkey, OUTPUT);
  pinMode(statuspin, INPUT);

  mySerial.println("AT");
  delay(2000);
  leserial();

  //TURN ON GPS
  mySerial.println("AT+ CGNSPWR =1");
  delay(2000);
  leserial();
}

void loop() {
  //GET LOCATION
  mySerial.println("AT+CGNSINF");
  delay(4000);
  leserial();
  delay(5000);
}

void leserial(){
  inputString = "";
  while (mySerial.available()>0){
    inChar = mySerial.read();
    inputString += inChar;
  }
  Serial.println(inputString);
}


texts: Logging PAR with quantum sensor and Arduino

texts:
I want to link a PAR quantum sensor (either Licor or Skye Instruments) to Arduino to log PAR, in order to measure light in a forest.
I have an Arduino Uno + data logging shield (with RTC, SD card and ADS1115) and have connected the PAR sensor via A0 to measure differential voltage (A0 –– S+ | S- –– GND | A1 –– GND). Code as follows:

  ads.setGain(GAIN_TWOTHIRDS);
  adc0 = ads.readADC_Differential_0_1();
  Voltage = (adc0 * 6.144)/pow(2, 15);
  Voltage = Voltage*1000; // conversion to millivolts

When I wire the Arduino to itself to measure a differential voltage (A0 –– 3V and A1 –– GND), it measures beautifully.

Furthermore, when I use a voltmeter to test the Voltage across the + - wires from the sensor, I get sensible readings.

Put the two together – nonsense. I get noisy V readings that don't make sense. When I cover the sensor my V is actually going up, not down as it should! I have tried changing the GAIN, but unfortunately this makes no difference to the problem.

I have been looking at PARduino for help/inspiration, but they include an amplifier in their setup, which is expensive and I'm not sure is necessary / would solve my problem.

Very new to Arduino. Any and all advice would be very much appreciated.


texts:
I have interfaced sd card and ADS1262 (ADC module) with Arduino mega board and sharing the SPI control pin i.e. SCK, MISO and MOSI.
I have found that sd card is not initialized and ADS1262 is giving garbage value.
Now if I remove the MISO pin of sd card then ADS1262 is giving right (although SD card is not initialized.)
Vice-versa, if I remove the MISO pin of ADS1262, sd card is initialized and working perfectly (although ADS1262 is giving garbage value.)

Certainly, there is issue of MISO pin. How can I share MISO pin with both slaves so that both can work properly.

Any comments please.

I am using shifter - TXS0108E.

For SPI interfacing, I have tested two slaves with Mega board and found the below result when MISO is connected with both slaves and MISO pin is removing one by one from slaves.

From Above result, I thing it may be the problem of MISO pin.

I am not getting the idea, how to solve the problem in SPI interfacing in multiple slaves.

Schematic: