texts: Can't send AT comands to ESP8266 on any baud rate

texts:
I have problem with baud rate. I have changed baud rate of esp from 115200 to 9600 with AT command AT+CIOBAUD. And everything worked fine until I wanted to change it back and executed command AT+CIOBAUD115200, after which everything I send trough arduino IDE serial monitor to ESP I get gibberish. I have tried all baud rated available in serial monitor but got nothing. Wiring stayed the same.

TX -> arduino RX
RX -> arduino TX
GND -> GND
CH_PD -> 3,3V
VCC -> 3,3V

I thought that if I can flash ESP firmware it will get back all default parameters, hence I tried flow these steps (link) but I stopped when executed esptool.py --port /dev/ttyACM0 erase_flash which got me

esptool.py v1.3
Connecting...................

A fatal error occurred: Failed to connect to ESP8266: Invalid head of packet ('\x00')

In some forums is said that to get rid of error I need to change baud rate, but nothings works for me.

Please advise how can I fix this problem.


texts:
I’ve got a quite weird behavior of DHT library.

I’ve got DHT22 sensor. If it’s signal cable is not connected, reading the sensor causes a problem: Arduino reboots or hangs in unpredictable places.

If I connect the signal cable again, the problem vanishes.

Is this normal behavior or some sort of bug? I think unsuccessful reading affects some part of Memory.

PS. The project is quite big and I can’t share the code here.

It happens that I found an evidence that dht object influences foreign memory. Look at this code:

DV("pClock->isInited 3", pClock->isInited); // prints 1
dht1.readHumidity();
DV("pClock->isInited 4", pClock->isInited); // print 0 !!!!
// nothing more can be called between these lines.

// DV is a macro which prints label and value.
// Both objects created before this.

DHT dht1(11, DHT22);
…
dht1.begin();
…
pClock = new ZhClock(); // uses RTC_DS1307
pClock->init(&rtc); // rtc is RTC_DS1307


texts: MQ4 gas sensor is not working with Arduino UNO

texts:
I am trying to detect LPG leakage by using MQ4 gas sensor.
I have made this circuit

My Arduino code is

int sensorValue;

void setup()
{
  Serial.begin(9600);      // sets the serial port to 9600
}

void loop()
{
  sensorValue = analogRead(0);
  Serial.println(sensorValue, DEC);
  delay(100);
}

On my serial monitor, I am getting values like

307
277
289
282
283
283
260
248
265
285
308
278
278
315
321
316
327

These values are not getting change even after putting sensor near gas lighter. Did I made any mistake in circuit or this sensor could be faulty ? Any help is appriciated.


texts:
EDIT
This seems to be something to do with the oscillators. Switching to the internal oscillator and writing straight avr-c allows me to run a basic blink program. Writing the same basic blink in arduino and flashing with the IDE (through serial or usbasp) results in a non functional program. I'd like to be able to use the oscillator because it doesn't look like I can get everything done in time at 8MHZ
I have an arduino mega 2560 which a few weeks ago was working fine. Now, I'm trying to output some data from it, and 've broken it down to a very, very basic proof of concept:
void setup() {
// put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
   // put your main code here, to run repeatedly:
   Serial.println("hello");
}

This prints:
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

indefinitely on the screen. If I change the baud to 115200, I get the "hello" and the newline, and slowly start getting garbage afterwards. If I switch to 234500, I get a few prints, and then nothing.
Adding a delay after the print does not change the frequency of the serial prints:
void loop() {
// put your main code here, to run repeatedly:
    Serial.println("hello");
    delay(100000);
}

They still come in immediately.
I have a feeling this has something to do with timing of an interrupt, but I'm not setting anything up. I plan to reflash and fix the fuses, but my usbASP cable is broken right now. Any other input on what might be going on here?
Edit:
This occurs on two different boards. I originally had some i2c devices (mag/gryo/barometer) on board, but those have since been removed. I have tried two different usb cables in two different USB ports. This might be on the host side?
Edit:
Both the TX and Rx lights are solid this whole time. Almost as if there's a loopback. My other laptop won't even boot right now. I'm concerned a surge from a storm last night might have taken out both of these machines
More testing:
Looking at the output on a scope, the board is actually only outputting an "h" character. If I do:
Serial.println('U');
delay(1000);

I get a square wave, so the delay doesn't run at all.
If I do:
Serial.println('U');
Serial.println('U'); //or any other character
delay(1000);
I get a U character over the scope, and then an empty serial frame. The delay still doesn't run, but it looks like the second println is exiting.
Even burning a new bootloader fails on these boards


texts:
I'm managing to upload a sketch to the ESP8266 01. I have been researching on internet but I'm not able to get it.

I have installed the libraries for Arduino IDE and my circuit is the ESP powered by 9V converted to 3.3V using a LD 3.3 converter. I tested the voltages and works fine. Also the led in ESP is on (red).
To connect to the computer I'm using a TTL USB cable without vcc connected only for tx and rx.

The commands for the ESP works fine (AT commands), but when I try to upload a sketch it shown the following error:

  espcomm_open failed

I also have connected to GP0 (ESP) a button to ground. The circuit is:

9V battery --> 3.3V converter --> ESP---> TTL

Anyone knows about that error and why could be? Because the AT commands works fine. Maybe I need to provide more information but not sure.

My goal is to do this tutorial:
https://learn.adafruit.com/downloads/pdf/esp8266-temperature-slash-humidity-webserver.pdf

Another problem that I have following that tutorial is that in Arduino IDE, I cannot setup esptool as programmer, because isn't there. I loaded the same library for esp


texts:
I need to measure (and record changes over a short time) the angle of a lever at a sub-degree resolution (The fulcrum can be the sensor) using an Arduino.

I've looked at rotary encoders, but even those with no detents have about 24 pulses per rotation. I need to measure only across a 90 degree arc. 24 pulses per rotation is 15 degrees per pulse. Which I guess results in a measurable resolution of 7.5 degrees!

I could add gears to increase the turns on the encoder, but that would increase the force required to move the lever.

Is there an option I'm not thinking of?


texts: loop() either stops working, or lcd stops working | buttons don't work

texts:
I'm using a Let's Start Coding Ultimate Kit 1 (it was a christmas present, don't ask) and I'm trying to use this as a typing sort of thing. I haven't implemented the actual letters though.

#include <MakerScreenXVI.h>;

MakerScreenXVI lcd;

int currentNumber = 1;
int ms = 0;
int totalMS = 0;
bool first = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(A0, INPUT);
  pinMode(A3, INPUT);

  lcd.begin();
  lcd.print("Success");
  lcd.setCursor(0,1);
  lcd.print(currentNumber);

}

void loop() {
  delay(200);
  changeNumber();
  delay(200);
}

void clearLCDLine(int line) {
        lcd.setCursor(0,line);
        for(int n = 0; n < 16; n++) // 20 indicates symbols in line. For 2x16 LCD write - 16
        {
                lcd.print(" ");
        }
}

void changeNumber() {
  if (digitalRead(A0) == LOW) {
    if (first == false) {
      clearLCDLine(1);
      first = true;
    } else {
      first = false;
    }
    currentNumber++;
    if (currentNumber == 27) {currentNumber = 1;}

    lcd.print(currentNumber);
  } else if (digitalRead(A3) == LOW) {
    currentNumber = currentNumber - 1;
    if (currentNumber == 0) {currentNumber = 26;}
    //clearLCDLine(1);
    lcd.print(currentNumber);
  }
}

For some reason, after it deletes the 1, it stops. Nothing is printed onto the screen, and nothing is cleared from it. How can I fix this?
Also, the buttons always return the LOW value. How can I fix this?


texts:
I want to run an Arduino autonomously - but although I apply a watchdog sometimes the systems hangs and can only be restarted by physically interrupting the power-supply (or hitting reset). So I need an external source to do that either after x hrs or based on a condition.

Instead of using another Arduino with a MOSFET or relay I am asking myself if this couldn't be done smarter with a pure electronic component like a timer or a capacitor. I could set a pin of the Arduino on high while it is active and let this charge a capacitor or something similar - if the time/energy exceeds a certain amount (because it hangs) this would connect the reset-pin of the Arduino to ground.

Any idea how this could be achieved and what component should be used?


texts: How can I call the constructor of a Class after it called once?

texts:
I have a problem with Classes.
I have a bunch of code, that code is uses Adafruit MQTT FONA library. I call the Class for make new Instance and Connect to specified server with this code;

Adafruit_MQTT_FONA mqtt(&fona, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

When I want to connect to another server, I call this Instance's constructor after it called once. But it don't let me to construct it again. How can I construct the same instance again after it constructed once?

void connectMqtt()
{
    Adafruit_MQTT_FONA mqtt(&fona, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
}

connectMqtt();

Thanks for helps! Have a good day!


texts: Do we need ARM build for arduino while interfacing R-pi and arduino

texts:
I wonder whats ARM build for Linux? Do we really need ARM build when we work with arduino? I need to integrate arduino and raspberry pi over wi-fi, I don't know whether I need ARM in this case. Also any quick learning tutorial for interfacing two of these hardware is appreciable

A newbie to Arduino. I hope fun learning with it


texts: Which libraries for DS1302 real time clock and WS2811 LED strip do not conflict?

texts:
I am making a custom wall-clock, and need the Arduino (Uno or Nano) to connect to a DS1302 real time clock module and a WS2811 LED chain.

So I’m using DS1302 for the clock, and FastLED for the lights. Individually these two libraries work fine, so I can either echo the time to the serial console, or I can drive the LEDs as I need.

But when I combine them there is some conflict happening and I get no LED output. The LED data goes over pin 6 and the clock uses pins 2,3,4 (these pins are customisable in code).

Even just adding a DS1302 initialisation to a working FastLED sketch causes no more LED output

#include <FastLED.h>
#include <DS1302.h>

#define NUM_LEDS 50
#define DATA_PIN 6

// Init the DS1302 - stops LEDs working
DS1302 rtc(2, 3, 4);

CRGB leds[NUM_LEDS];

void setup() {
  FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS);
}

void loop() {
  for (int i=0; i<NUM_LEDS;i++) {
    leds[i] = CRGB::Red;
  }
  FastLED.show();
  delay(100);
}

What are my troubleshooting steps - should I try alternative libraries, or could I dig into the libraries themselves and see what hardware resources they might be using?

I guess as both the lights and the clock probably operate over a serial protocol, it could be a conflict with the serial drivers - maybe both using the same time-critical operations.

Edit: inserted sketch which demonstrates the issue


texts: How to avoid the code interrupting itself?

texts:
I have this code, which I am using with a potentiometer to control the speed of a automotive fuel injector. In it, I have specified how long the injector shall stay open by using the delay functions. However, whenever the code runs into a delay call, it pauses the whole code for that amount of time. Although it's not significantly long, it would still be better if it could keeping running analogInput and at the same time run through the if statements, without any interference from either. So basically run two different process simultaneously.

I remember reading somewhere that this is possible with threading? But do you need a library for that? I know Python has a threading library built in, and you can actually use it pretty easily, but what about Arduino? How could I run these two process at the same time?

Here's my code:

#define in1 12

void setup(){
 Serial.begin(9600);
 pinMode(in1, OUTPUT);
}

void loop(){
 float rotationValue = analogRead(A1);            //read raw input from potentiometer
 float percentValue = rotationValue / 10.23;      //convert to percent 0-100
 Serial.println(percentValue);                    //print it to screen
 if(percentValue >= 0.0 && percentValue <= 1.0){
  digitalWrite(in1, LOW);                         //injector 1 off
 }
 else if(percentValue > 1.0 && percentValue <= 25.00){    //cycle at 100 millisec.
  digitalWrite(in1, HIGH);
  delay(100);
  digitalWrite(in1, LOW);
  delay(100);
 }
 else if(percentValue > 25.00 && percentValue <= 50.00){    //cycle at 50 millis.
  digitalWrite(in1, HIGH);
  delay(50);
  digitalWrite(in1, LOW);
  delay(50);
 }
 else if(percentValue > 50.00 && percentValue <= 75.00){      //cycle at 25 millis.
  digitalWrite(in1, HIGH);
  delay(25);
  digitalWrite(in1, LOW);
  delay(25);
 }
 else{              //cycle at 10 millis.
  digitalWrite(in1, HIGH);
  delay(10);
  digitalWrite(in1, LOW);
  delay(10);
 }
}


texts: Arduino clock needed to print the time a button is pressed while continuing to count the time?

texts:
I'm making a clock using an arduino uno and a compatible freetronics screen. So far it can count the time in a 24 hour loop after which it repeats and counts again. The screen had a number of buttons built onto it and I want to get it so that when one of the buttons on the screen is pressed it prints the time that it was pressed on the top line of the screen while continuing to count and print the time on the second line of the screen.

How can I edit my code below to do this when a button is pressed? What sort of command do I need to add?

#include <Wire.h>
#include <LiquidCrystal.h>

#define MILLIS_OVERFLOW 34359738

/**
* Clock Variables
*/
unsigned long currentMillis, previousMillis, elapsedMillis;
int seconds = 0, minutes = 0, hours = 8;

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

void setup()
{
  Serial.begin(9600);
    lcd.begin( 16, 2 );

}

void loop()
{
setClock();

/**
 * After set clock now you have 3 int variables with the current time
 */
 //seconds
 //minutes
 //hours
 lcd.setCursor ( 0, 1);
 lcd.print(hours);
 lcd.print(":");
 lcd.print(minutes);
 lcd.print(":");
 lcd.print(seconds);
 lcd.print(":");
 lcd.print(elapsedMillis);

}

void setClock()
{
currentMillis = millis();
/**
 * The only moment when currentMillis will be smaller than previousMillis
 * will be when millis() oveflows
 */
if (currentMillis < previousMillis){
    elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
} else {
    elapsedMillis += currentMillis - previousMillis;
}

/**
 * If we use equals 1000 its possible that because of the mentioned loop limitation
 * you check the difference when its value is (999) and on the next loop its value is (1001)
 */
if (elapsedMillis > 999){
    seconds++;
    elapsedMillis = elapsedMillis - 1000;
}

if (seconds == 60){
    minutes++;
    seconds = 0;
}
if (minutes == 60){
    hours++;
    minutes = 0;
}
if (hours == 24){
    hours = 0;
}

previousMillis = currentMillis;
}

Any help will be greatly appreciated, thanks


texts: How to read ASCII values from AT24C32 IC using Arduino? And what is serial.begin(?) in that EEPROM?

texts:
#include<Wire.h>
#include<Eeprom24C32_64.h>
#define EEPROM_ADDRESS 0x000

void setup() {
  Serial.begin(9600);
  eeprom.initialize();
  const word address = 0x000;
  const byte count = 94;
  byte inputBytes[count] = { 0 };
  byte outputBytes[count] = { 0 };
  Serial.println("Read bytes from EEPROM memory...");
  eeprom.readBytes(address, count, outputBytes);
  Serial.println("Read bytes:");
  for (byte i = 0; i < count; i++) {
    Serial.write(outputBytes[i]);
    Serial.print(" ");
  }
  Serial.println("");
}

void loop() {
}

Next code... I have tried many sketches.

#include <EEPROM.h>

void setup () {
  Serial.begin (115200);
  Serial.println ();
  for (int addr = 0x0000; addr < 0x0010; addr++) {
    Serial.print ("Address = ");
    Serial.print (addr, HEX);
    Serial.print (", value = ");
    Serial.println (EEPROM.read(addr), HEX);
  }
}  // end of setup

void loop () {
}

And most of the sketches check the internal EEPROM of the Arduino, not the external, stored on address 0x000. I want to read data from external AT24C32.


texts: Light up multiple LEDs with standard Arduino Uno

texts:
I am trying to find out if it is possible to light up multiple LEDs with a standard Arduino Uno. Say I have 500 LEDs and logically I give each one of them a number from 1 to 500. In my test scenario I'd like to say something like "LED No 275 On" and as a result only have this single LED turning on while all others remain off.

Is there a way to do that at all? Or will I have to use many different Arduino Unos for that?


texts:
Arduino newbie here.

I'm thinking about building an Arduino-based light switch to control the Philips Hue light system in my living room. I have standard wall light switches that power ceiling lamps, and I basically want all Hue lamps that are scattered around the room to be on when the switch is on, and off when the switch is off, so that I don't necessarily need the app or the Hue remote to turn the room's lights on.

My idea is to install an Arduino on the ceiling instead of a normal lamp, so that its power supply is switchable through the light switch.

I would configure it as a Hue remote control, e.g. with ArduinoHue; if all works well, this would control the Hue lamps directly via ZigBee or via WiFi through the bridge - in both cases without having to use additional wiring.

Whenever it gets power, I would have it turnOn() all lamps, and whenever its power supply is turned off, I would have it turnOff() all lamps.
The first part seems simple to me, the second part - not so much.

So here's my question:
Can I execute code in the event of the Arduino losing power, i.e. turn off my Hue lights with its last energy before shutting down? Is there maybe some hardware configuration that would allow me to detect the power off event and retain enough energy through a battery or capacitors to still run the code?

I have never worked with Arduino before, but I do have some colleagues that can help me out when there's trouble.


texts:
I have a project that is part of a larger repository, and shares header files with non-Arduino C programs.

I know that it's possible to use these headers by copying them to the libraries folder, or the sketch folder, but I would rather use them with a relative path (which seems to not work), so I can avoid copying files around for every repository clone or update.

Is there a solution that doesn't involve moving/copying the header file?

EDIT:
Although there is no full solution for this question,
I have since found that using the PlatformIO
IDE instead solves the problem.


texts:
I have read some conflicting sources about what pins have internal pullup resistors available for the Attiny85 microcontroller. Can all I/O pins work with INPUT_PULLUP, or just some of them? And if so, which ones?

Thanks!


texts: Pressing button stops listening on nrf24l01

texts:
I have been tinkering for 2 days to manage send and receive between 2 arduinos. My code is bellow:

Arduino 1:

#include <SPI.h>
#include <RF24.h>
#include "printf.h"
#define LED 2
#define RF_CS 8
#define RF_CSN 9
RF24 radio(8,9);
String datargb = "rgb: 000000005";
char chartosend;
char inchar;
String inradio;
int endchar = '~';
void check_radio(void);
void setup() {
  // put your setup code here, to run once:
Serial.begin(115200);
  printf_begin();
  radio.begin();
  radio.setRetries(15,15);
  radio.openWritingPipe(0x080C600C01LL);
  radio.openReadingPipe(1,0x080C600C71LL);
  radio.setPALevel(RF24_PA_MAX);
  radio.setAutoAck(true);
  radio.printDetails();
  attachInterrupt(0, check_radio, FALLING);
  radio.stopListening();
}

void loop() {
  // put your main code here, to run repeatedly:
int lnth = datargb.length();
  for(int i=0; i<lnth; i++){
      chartosend=datargb.charAt(i);

      while(!radio.write( &chartosend, sizeof(chartosend) )){}

      Serial.println("sent");
  }
  radio.write(&endchar,1);
}
void check_radio(void){

  bool tx,fail,rx;
  radio.whatHappened(tx,fail,rx);

  if(rx){
    Serial.println("interrupt!!");
radio.startListening();
    radio.read( &inchar, sizeof(inchar) );
    inradio+=inchar;
    Serial.println(inchar);
    if(inradio.endsWith("~")){
      Serial.println(inradio);

      if(inradio.startsWith("rgb: ")){
        analogWrite(6,inradio.substring(5,8).toInt());
        analogWrite(9,inradio.substring(8,11).toInt());
        analogWrite(5,inradio.substring(11,14).toInt());
      }
      inradio = "";
      radio.stopListening();
    }
  }
}

Arduino 2:

#include <SPI.h>
//#include <nRF24L01.h>
#include <RF24.h>
#include "printf.h"
//#include <RF24_config.h>
RF24 radio(8,10);
char data;
char chartosend;
char endchar = '~';
String inradio;
void check_radio(void);
String datargb = "To mounti tis manas tou nrf24";
void setup() {
  // put your setup code here, to run once:
  pinMode(9, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, INPUT);
  attachInterrupt(1, check_radio, FALLING);
  Serial.begin(115200);
  printf_begin();
  radio.begin();
   //radio.setRetries(2,15);
    // open pipe for writing
    radio.openReadingPipe(1,0x080C600C01LL);
    radio.openWritingPipe(0x080C600C71LL);
    radio.setPALevel(RF24_PA_MAX);
    radio.startListening();
    radio.printDetails();
    radio.setAutoAck(true);
}

void loop() {
  // put your main code here, to run repeatedly:
if(digitalRead(7)==HIGH){
  radio.stopListening();
  for(int i=0; i<28; i++){
      chartosend=datargb.charAt(i);
      while(!radio.write( &chartosend, sizeof(chartosend) )){}
      //Serial.println("sent");
  }
  radio.write(&endchar,1);

  while(digitalRead(7)==HIGH){}
  radio.startListening();
}
}
void check_radio(void){

  bool tx,fail,rx;
  radio.whatHappened(tx,fail,rx);

  if(rx){
    Serial.println("interrupt!!");
//radio.startListening();
    radio.read( &data, sizeof(data) );
    inradio+=data;
    Serial.println(data);
    if(inradio.endsWith("~")){
      Serial.println(inradio);

      if(inradio.startsWith("rgb: ")){
        analogWrite(6,inradio.substring(5,8).toInt());
        analogWrite(9,inradio.substring(8,11).toInt());
        analogWrite(5,inradio.substring(11,14).toInt());
      }
      inradio = "";
      //radio.stopListening();
    }
  }
}

Arduino 2 receives all data from ar1 but when I press the button attached to the pin 7 arduino 2 stops listening and only sends the first character of the string.


texts:
I want to use Arduino DUE board as a FTDI programmer.

The task is to program ESP32 module which is connected to the Arduino Serial port.

I can use only DUE Native port. There is no DUE programming port in my design.


texts: How to choose between AM230x and DHT22 temperature and humidity sensors?

texts:
I'm looking forward to getting an accurate humidity and temperature sensor.

Right when I decided to go with a DHT22 module, I saw AM230x (AM2301, for example).

How do I choose between DHT22 and AM2301?


texts: Mega 2560 powered with 7V don't work correctly

texts:
I have an Arduino Mega 2560  with a GPRS seeedstudio shield and an USB Host CircuitsAtHome shield which work fine when powered with USB or with an adjustable voltage regulator set at 8V.

When I set this voltage regulator at 7V (minimum voltage from the spec to get the better efficiency) I am still reading 5V and 3.3V on the pins of the Arduino and all the leds of the Arduino and the GPRS shield seems fine but the USB Host CircuitsAtHome shield seems to not work properly.
I cannot debug it using the console because if I plug the USB cable, everything works fine...

Why 7V fail while 8V is ok?

The adjustable voltage regulator can provide up to 5A which is plenty.


texts: Doesn't Arduino reports DSR (Data Set Ready) correctly?

texts:
I was told, that when computer opens port, it sends DTR (Data Terminal Ready) signal to Arduino, which initiates Arduino reboot.

This looks like part of DTR / DSR flow control. According to this, in response to DTR, Arduino should no only reboot, but also raise DSR (Data Set Ready) signal when it is ready to receive data

And computer should wait for it.

Does it happen so?


texts: NRF24L01 integrated antenna exposed out of the box

texts:
I'm going to try my hand at making a few sensors that are to report status to a central server. To make them wireless, I'm going with nRF24L01 modules. I intend to enclose the sensors (Arduino Mini Pro + nRF24L01 + battery pack + a couple of other small components) in a simple PVC box.

A couple of the sensors would be about 10 meters away from the server, which, as far as specifications go, is about the maximum range of the radio modules. Especially the ones with the integrated antenna that I'm using. I thought that maybe I could squeeze some radio performance by exposing the antenna, so that the radio signal isn't attenuated by the PVC case. I could carve a small opening in the lid and have the nRF24L01 stick out, so that the electronics would be protected inside but the antenna strip would enjoy open air.

I would like some thoughts on this idea. I'm especially trying to understand if I just had the most novel idea ever, since I can't seem to find anything about it on the net. Has anyone ever tried this in real life? Does it make sense? Is it worth the trouble?  I'm not looking for a theoretical analysis (I get that fine), only for actual experience. Thank you.


texts: How can I connect nearly 450 LEDs to an arduino without drawing too much current?

texts:
The question seems simple, but there's more to it:

I'm connecting 4 74HC595 shift-registers to an arduino pro micro.
28 of the 32 outputs will be used to control LED segments of numbers.
Each segment uses 14-20 LEDs and so I will be using a transistor for each segment.
Now here's my problem: With the maximum amount of LEDs activated (at time 08:08), the LEDs will draw nearly 10A. How can I use another transistor to make the shift-registors work with the arduino even though it shouldn't be drawing all current from the arduino, but from an external power source. I have found a suitable adapter from 230V to 5V 12A. The 12A is just to ensure that nothing goes wrong. The LEDs alone will draw 9.76A.

I know how to connect the arduino to the power source, but how do I run extra wires from the power source around the arduino to provide the LEDs their power?


texts: Converting a standard setup/loop sketch to a low power application?

texts:
Suppose I have a typical setup/loop style sketch, such as this one which turns on an LED when a button is pressed.

How do I modify this so that it enters low power mode, awakes on the button press, and puts itself back into low power mode when its logic has finished?

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  // desired: enter low power mode here
}
void loop() {
  int buttonState = digitalRead(buttonPin);
  // desired: awake from low power mode here
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
    delay(1000);
    digitalWrite(ledPin, LOW);
  }
  // desired: back to low power mode here
}


texts: Not detecting Arduino Mega 2560. It worked before but now not detecting

texts:
I am using Windows 8.1 64 bit. I have an Arduino Mega 2560. I configured and installed it with the Merlin firmware before. I had a system format in between. I tried to connect my Arduino again.

I have the following problems:

Not detecting any hardware when plugging in the Arduino board: the green LED is on and the yellow LED is blinking. I checked the Device manager. It doesn't come in either COM ports or other devices. (The last time it came in COM ports as Arduino Uno). I installed legacy hardware on COM 3 (which was used before) and tried to update the driver from a newly downloaded version of Arduino. No success. I disabled the certification signature requirement from boot menu and tried: again no success.
The serial port on Arduino is greyed out.

I need some help. I am running out of ideas. I tried uninstalling COM port. I cleaned the registry with CCleaner. I uninstalled all Arduino software. I rebooted the system. I downloaded everything again, then connected the board. Still not detecting the new hardware. :P

Help me out.


texts: Make an LED Turn ON after pressing a push button switch for five times. Add a reset switch to turn OFF the LED whenever the reset switch is pressed

texts:
**void setup()

{

  pinMode(11, OUTPUT);

  pinMode (4,INPUT);

}

void loop()

{

  int y= digitalRead(6); // push button 2

  static int counter {} ;

  int x= digitalRead(4);// push button 1

  if (x==1&& y==0 )

    counter++;

else if (counter == 5) // If counter is pressed 5 times

{

  digitalWrite(11, HIGH); // Turn on the LED

}

if (counter >= 5) // If counter is greater than 5 led will still on

{

  digitalWrite (11, 1);

}

  else if

   (y==1&& x==0 ) // if pressed push button 2  led of
  {

    digitalWrite(11,0);

}

  counter = 0; // Make counter variable = 0

}


texts: YUN. How to reset the micro controller from linux?

texts:
As the title, I'd like to reset the Arduino sketch from the linux machine. Is it possible? how?

One solution could be to save the hex file inside the sd card and then upload it via the lua sketch but I think there is a smarter solution.


texts:
I'm new to arduinos and have not been able to find/create a working bit of code for my project. I'd like to control several different relays (standard 5v optical relays) with push buttons. I want one pushbutton1 to turn on/off relay1, pushbutton2 to turn on/off relay 2, etc.

I ran into troubles using delay statements as debouncers because I guess it locked out the remainder of the code while it ran? I then tried to use a flagging approach covered here:

https://github.com/VRomanov89/EEEnthusiast/blob/master/03.%20Arduino%20Tutorials/01.%20Advanced%20Button%20Control/ButtonSketch/ButtonSketch.ino

const int numOfInputs = 2;
const int inputPins[numOfInputs] = {2,3};
const int outputPin = 10;

int LEDState = 0;
int inputState[numOfInputs];
int lastInputState[numOfInputs] = {LOW,LOW};
bool inputFlags[numOfInputs] = {LOW,LOW};
int inputCounters[numOfInputs];

long lastDebounceTime[numOfInputs] = {0,0};
long debounceDelay = 50;

void setup() {
  for(int i = 0; i < numOfInputs; i++) {
    pinMode(inputPins[i], INPUT);
    digitalWrite(inputPins[i], HIGH); // pull-up 20k
  }
  Serial.begin(9600);
  pinMode(outputPin, OUTPUT);
}

void loop() {
  setInputFlags();
  resolveInputFlags();
  resolveOutputs();
}

void setInputFlags() {
  for(int i = 0; i < numOfInputs; i++) {
    int reading = digitalRead(inputPins[i]);
    if (reading != lastInputState[i]) {
      lastDebounceTime[i] = millis();
    }
    if ((millis() - lastDebounceTime[i]) > debounceDelay) {
      if (reading != inputState[i]) {
        inputState[i] = reading;
        if (inputState[i] == HIGH) {
          inputFlags[i] = HIGH;
        }
      }
    }
    lastInputState[i] = reading;
  }
}

void resolveInputFlags() {
  for(int i = 0; i < numOfInputs; i++) {
    if(inputFlags[i] == HIGH) {
      // Input Toggle Logic
      inputCounters[i]++;
      updateLEDState(i);
      printString(i);
      inputFlags[i] = LOW;
    }
  }
}

void printString(int output) {
      Serial.print("Input ");
      Serial.print(output);
      Serial.print(" was pressed ");
      Serial.print(inputCounters[output]);
      Serial.println(" times.");
}

void updateLEDState(int input) {
  // input 0 = State 0 and 1
  if(input == 0) {
    if(LEDState == 0) {
      LEDState = 1;
    }else{
      LEDState = 0;
    }
  // input 1 = State 2 to 6
  }else if(input == 1) { // 2,3,4,5,6,2,3,4,5,6,2,
    if(LEDState == 0 || LEDState == 1 || LEDState > 5) {
      LEDState = 2;
    }else{
      LEDState++;
    }
  }
}

void resolveOutputs() {
  switch (LEDState) {
    case 0:
      digitalWrite(outputPin, LOW);
      break;
    case 1:
      digitalWrite(outputPin, HIGH);
      break;
    case 2:
      analogWrite(outputPin, 30);
      break;
    case 3:
      analogWrite(outputPin, 70);
      break;
    case 4:
      analogWrite(outputPin, 100);
      break;
    case 5:
      analogWrite(outputPin, 155);
      break;
    case 6:
      analogWrite(outputPin, 255);
      break;
    default:
    break;
  }
}

But was unable to alter the code to get it to work... could someone help me write a bit of code which will allow me to do what I want it to do? I'd rather not buy a matrix-style shield to accomplish this, but I will if I have to.

What I want to do:

Turn on relay1 by pressing momentary pushbutton1
Turn off relay1 by pressing momentary pushbutton1
Turn on relay2 by pressing momentary pushbutton2
Turn off relay2 by pressing momentary pushbutton2
etc.
etc.

Thank you in advance!


texts: data integrity when interrupts are too fast

texts:
I have an encoder that fires ~54000 interruptions per second.
This is way too fast for my arduino uno.
But I'm trying to see what I can get from it anyway. For science.

unsigned long tickACount = 0;
unsigned long tickBCount = 0;

void myInterrupt(){
  tickACount++;
  tickBCount++;
}

Then in my main loop, every second I print tickACount and tickBCount.
I can see my arduino is able to handle only about 2050 interrupts per second. No surprise here.

What surprises me, is that tickACount and tickBCount have different values! tickBCount is consistently higher that tickACount.

Ok now I switch them to volatile. And according to the documentation, volatile only makes sense for 8bit values. The counts will eventually overflow but it doesn't really matter. I just want to see if those two variables are still different.

volatile uint8 tickACount = 0;
volatile uint8 tickBCount = 0;

void myInterrupt(){
  tickACount++;
  tickBCount++;
}

The result is that the two values are still different.
Also, wrapping them into some ATOMIC macro does not help.

From what I read, interrupts cannot be interrupted.
And beside, if my interrupt was aborted midway, then tickACount would be higher than tickBCount, not the other way around.

Therefore, what can be the explanation for those two variables to be different?

Thank you for any idea!


texts:
I have been trying to stream data into excel for my arduino leonardo. I have been trying to record the CO2 levels and volatile organic compounds into excel. I've used a comma to separate however nothing is showing up. I am unsure if there is something missing from my code?
#include "Adafruit_CCS811.h"

Adafruit_CCS811 ccs;

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

  Serial.println("CCS811 test");

  if(!ccs.begin()){
    Serial.println("Failed to start sensor! Please check your wiring.");
    while(1);
  }

  // Wait for the sensor to be ready
  while(!ccs.available());
}

void loop() {
  if(ccs.available()){
    if(!ccs.readData()){
      //Serial.print("CO2: ");
      Serial.print(ccs.geteCO2());
      Serial.print(",");
      //Serial.print("ppm, TVOC: ");
      Serial.println(ccs.getTVOC());
    }
    else{
      Serial.println("ERROR!");
      while(1);
    }
  }
  delay(500);
}


texts:
I am making a high range and fast Obstacle detection system ,
HC-04 is slow for that, other sensor don't have the range and Lidar is too costly.

Any idea how to make a long range(more than 10m) high speed Obstacle detection system


texts: Should L, TX, RX led light on while connected with laptop

texts:
Dear Sir,
               I need to know that should led light named as L, TX, RX should be on when we connect it with laptop?
Because when I connect it with laptop led light turns on for 1 or 2 second then turns off. That's why I am asking you this question.
                 Hoping for a favourable answer.
Your's faithful,
Nir Patel.


texts: Arduino Uno with CC3000 WiFi Shield cannot be initialized

texts:
I am working on an Arduino Uno and CC3000 WiFi shield. I interfaced it over my Arduino and added the SparkFun library SFE_CC3000_Library. Then I opened the TestBoard example, but it hangs on setup in the first command wifi.init().

How can I solve this problem, and how can I enable debug mode?

Here's the code

#include <SPI.h>
#include <SFE_CC3000.h>
#include <utility/netapp.h>

#define DEBUG     1
// Pins
#define CC3000_INT      2   // Needs to be an interrupt pin (D2/D3)
#define CC3000_EN       7   // Can be any digital pin
#define CC3000_CS       10  // Preferred is pin 10 on Uno

// Constants
#define FW_VER_LEN      2   // Length of firmware version in bytes
#define MAC_ADDR_LEN    6   // Length of MAC address in bytes

// Global Variables
SFE_CC3000 wifi = SFE_CC3000(CC3000_INT, CC3000_EN, CC3000_CS);

void setup() {

  int i;
  unsigned char fw_ver[FW_VER_LEN];
  unsigned char mac_addr[MAC_ADDR_LEN];

  // Initialize Serial port
  Serial.begin(115200);
  Serial.println();
  Serial.println("----------------------------");
  Serial.println("SparkFun CC3000 - Board Test");
  Serial.println("----------------------------");

  // Initialize CC3000 (configure SPI communications)
  if ( wifi.init() ) {
    digitalWrite(13, HIGH);
    Serial.println("CC3000 initialization complete");
  } else {
    Serial.println("Something went wrong during CC3000 init!");
  }

  // Read and display CC3000 firmware version
  if ( wifi.getFirmwareVersion(fw_ver) ) {
    Serial.print("Firmware version: ");
    Serial.print(fw_ver[0], DEC);
    Serial.print(".");
    Serial.print(fw_ver[1], DEC);
    Serial.println();
  } else {
    Serial.println("Could not read firmware version from CC3000");
  }

  // Read and display CC3000 MAC address
  if ( wifi.getMacAddress(mac_addr) ) {
    Serial.print("MAC address: ");
    for ( i = 0; i < MAC_ADDR_LEN; i++ ) {
      if ( mac_addr[i] < 0x10 ) {
        Serial.print("0");
      }
      Serial.print(mac_addr[i], HEX);
      if ( i < MAC_ADDR_LEN - 1 ) {
        Serial.print(":");
      }
    }
    Serial.println();
  } else {
    Serial.println("Could not read MAC address from CC3000");
  }

  // Done!
  Serial.println("Finished board test");

}

void loop() {

  // Do nothing
  delay(1000);
  Serial.println("Loop_Problem");

    }


texts: Programming arduino via bluetooth module issue

texts:
I followed a tutorial on how to setup arduino and bluetooth so it can be programmed without usb cables. I didn't use capacitors or resistors asthere doesn't seem to be a need for them. I have the serial output appearing on arduino serial console via bluetooth (no usb cable connected). Since the is a working connection that means it is working to a point. However when trying to upload I get "avrdude: stk500_getsync(): not in sync: resp=0x4c" error.

I didn't connect pin 32 of hc-05 to arduino reset pin yet, could that be the issue? I don't actually need arduino to be reset since I can just kill the power to it manually at least for now. I also used 9600 as baud rate instead of 115200 as in the tutorial, because my arduino code used 9600 but maybe I misunderstood this and it actually needs to be 115200 regardless or my baud rate in arduino code?

What else could be the cause?

Edit 1:

From the answer by @sachleen I changed the baud rate as per the tutorial and soldered pin 32 of the hc-05 module to rst pin of arduino.

After baud rate change opening arduino serial console no longer outputs anything. Why did this happen? I was getting serial output before when baud rate of hc-05 was 9600.

After soldering the rst pin arduino also seems to reset after serial console is opened. I did not add the capacitor, is it required and if so why? I also excluded resistors since it seems they are only for voltage reduction from 5v to 3V (my arduino is 3.3V version).


texts: MPU-9250 : How to convert pitch (+90/-90) to 360 degree?

texts:
I'm using Arduino Uno with MPU-9250 to find roll, pitch and yaw.

Everything works fine but I want to covert pitch from (+90/-90) to 360 degree.

I'm using this code:

vec.setX(atan2(2.0 * (m_data[2] * m_data[3] + m_data[0] * m_data[1]),
        1 - 2.0 * (m_data[1] * m_data[1] + m_data[2] * m_data[2])));

vec.setY(asin(2.0 * (m_data[0] * m_data[2] - m_data[1] * m_data[3])));

vec.setZ(atan2(2.0 * (m_data[1] * m_data[2] + m_data[0] * m_data[3]),
        1 - 2.0 * (m_data[2] * m_data[2] + m_data[3] * m_data[3])));

m_data[0] = scalar;

m_data[1] = x;

m_data[2] = y;

m_data[3] = z;

What should I do?


texts:
I'm having trouble adding attachInterrupt in a library that I am creating. I researched a lot, and I noticed that this is a common mistake, but do not quite understand the answers I found.

The error in question is this:

sketch_nov04a.ino: In function 'void setup()':
sketch_nov04a:10: error: argument of type 'void (Teste::)()' does not match 'void (*)()'

My library is as follows:

Teste.h

#ifndef TESTE_H
#define TESTE_H
#include <Arduino.h>

class Teste
{
public:
    volatile long lastWindIRQ;
    volatile byte windClicks;

  void wspeedIRQ();
};
#endif

Teste.cpp

#include "Teste.h"

void Teste::wspeedIRQ()
{
  if (millis() - this.lastWindIRQ > 10)
  {
    this.lastWindIRQ = millis();
    this.windClicks++;
  }
}

my implementation

#include <Teste.h>

Teste teste;

void setup()
{
  Serial.begin(9600);
  pinMode(2, INPUT);
  digitalWrite(2, HIGH);
  attachInterrupt(0, teste.wspeedIRQ, FALLING);
}

void loop()
{
  Serial.println(teste.windClicks);
  delay(3000);
}

EDIT: Updated the error and corrected the problem cited by Ignacio


texts: Using VMA-02 / KA-02 Sound Shield to get line-in input on arduino

texts:
I bought this VMA-02 audio shield: http://www.velleman.co.uk/contents/en-uk/p623_vma02.html

I want it to get the data from line-in to line-out but with reading it in my arduino scetch first (e.g. for analysis later).

There's a example project to download here: http://www.apogeekits.com/Zip_Files/ka02-sample-code.zip

But I don't know whether it's possible to get the sound input anyway and if yes, with which pins I can read the input / write the output?


texts:
I have the following problem, the arduino is receiving a command like

LCD,Display line text one, Display line text two

I use an strcmp to match the beginning of the string that works but now I would like to ignore the beginning of the string (LCD) and scan in the next 2 variables until the comma to 2 new variables.

                sscanf(Command, "%[^,]%[^,]%[^,]", &dummy, &lcd_display_l1, &lcd_display_l2);

I don't know if it's possible to ignore the first variable (which would be the LCD) but I setup a dummy variable for it anyway what I not going to use.

All I get with this is the LCD in the dummy the other 2 does not fill up.
I have tried this syntax:

https://support.microsoft.com/en-us/kb/38335

Doesn't work either. Any ideas?


texts: Arduino Serial Communication Between 2 Uno

texts:
I'm trying to get two arduino uno to communicate. The slave reads a temp sensor as an analog value, then converts it to degrees C, then sends that value to the master, the master then prints the value to the serial monitor. This is the code I have thus far.

for the slave

const int tempPin = A0;

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

  void loop() {

   //read sensor data to a variable
   float volt = analogRead(tempPin) * 0.004882814;
   float degC = (volt - 0.5) * 100.0;
   Serial.println(degC);

   delay(2000); //Not to flood serial port
  }

this is the code for the master

float tempC;
void setup(){
  Serial.begin(9600);
  delay(2000);
 }

  void loop() {
 /**  check if data has been sent from the computer: */
 while (Serial.available()) {
 /* read the most recent byte */
    tempC = Serial.read();     //now byteRead will have latest sensor
                              // data sent from Arduino1

    Serial.println(tempC);
  }
}

My issue is that I am reading on the serial monitor 4 different 2 integer values


texts: Problem using ICSC (by majenkotech) in RS485 bus

texts:
I want to communicate with an RS485 Bus consisting of 5 Arduino Pro Minis as slaves and one Arduino Mega 2560 as Master. I found a great library for this.

According to the documentation provided by the author of library I can use:

ICSC icsc(1, 9600, 7); //ID, BaudRate, DEpin

But I also have to define a Serial port for ICSC to work with:

ICSC icsc(1, 9600, Serial1);

I cannot mix these two sentences. I mean I cannot define both DEpin and Serial port for the ICSC in one sentence. But I need it to be defined. I don't want to use Serial for that, which I need for Serial Monitor. I want to use Serial1 for this. What can I do? I couldn't find any updated documentation about this.

UPDATE:

I found out how to define Serial port and DEpin for ICSC. The problem is I cannot get an answer!

Here is Master code:

#include <ICSC.h>
ICSC icsc(Serial1, 1, 7); //Stream, ID, DEpin

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  icsc.begin();
  icsc.registerCommand('R', &showTemperature);
}

void loop() {
  icsc.send(2, 'T', 0, NULL);
  icsc.process();
}

void showTemperature() {
  Serial.println("ACK");
}

And here is the Slave code:

#include <ICSC.h>
ICSC icsc(Serial, 2, 7); //Stream, ID, DEpin
String strAck = "ProMini2:ACK";

void setup() {
  Serial.begin(9600);
  icsc.begin();
  icsc.registerCommand('T', &sendTemperature);
}

void loop() {
  icsc.process();
}

void sendTemperature() {
  icsc.send(1, 'R', sizeof(strAck) + 1, (char*)&strAck);
}

Assume that there is just one slave and one master. I tried this code but got no answer. Where is the error?


texts: How do I execute some code at a certain time without RTC module?

texts:
I am building a project when I need my arduino to execute some code at two given hours of the day, for example one at 19:00 and another at 06:00. I know that with a RTC module I can do this easily, however how can I do that without a RTC module? I do not want to have to connect my arduino to a computer neither to the internet. It does not also have to be precise, a couple of minutes off would be ok.

My board is an Uno R3.


texts: Looking for software allowing for Arduino-based project "mocking" / "wireframing"

texts:
I'd like to be able to import a number of components (e.g Arduinos, MPU6050s, displays, motor drivers, LEDs, etc) into an app of some sort then be able to wire those components to each other for the purpose of being able to refer to this crude schematic at a later point or to share it with others. I tried importing things into Eagle, but that seemed like an absolute overkill (if Eagle can be used for something like this, what would the best approach be?). Does software that solves that particular issue exist? Think of it like wireframing for hobby electronics projects...

Please forgive the absolute layman explanation.


texts: Weight Measurement System using arduino and load cell

texts:
I want to use a load cell (Capable of measuring up to 1 ton) connected to a arduino board.
I am a beginner, my questions are as follows :
1. How to calculate the current generated by the load cell ?
2. If current is too high, how will We make the arduino use the current to display weight ?

p.s If you know some helpful articles that might help me learn, please suggest.


texts: Scroll one line of text while another line is static on a SSD1306 OLED

texts: I have an SSD1306 OLED that I have connected to a Wemos D1 Mini. It works like a charm, but I was wondering if it was possible to have two lines of code, where one line is static, and the other one scrolls? No example on the web as far as I have tried to find.


texts:
When a String variable is declared and modified inside a function, where does it go? To the heap(as string declaration is a part of dynamic memory allocation) or to the stack(as it is a part of function)? And is the space regained after the function goes out of the scope?
For example

void loop()
{
  Serial.println(foo("def"));
  while(1);
}

String foo(String arg1)
{
 String test = "abc";
 test = test + arg1;
 return test;
}

So, in this case, the variable "test" is declared in stack or heap? And this space is regained at the end or not?

Modified:
What if inside loop variable is declared like below?

String foo_test = F("def");
Serial.println(foo(foo_test));

In this case what will be the status of variables?


texts: Arduino trim: does it remove the \n as well?

texts:
According to the manual:

https://www.arduino.cc/en/Reference/StringTrim

Trim strips one or more whitespaces from the beginning and the end. Does it also removes tabulators and \n ?

I have the following code which works:

 while (Serial.available()) {   // something came across the serial
      char c = (char)Serial.read();
      Command += c;
      Command.trim();
      if (c=='\n')
         {
           Complete =true;
         }
   if (Command.length() >0 && Complete) {

        if (Command == "LED_ON") {
               // Do stuff
        }

Although I'm not sure that it is working because of the last if statement which says: if (Command == "LED_ON") ignores the ending \n and say ok it matched OR Command.trim() really takes off that \n.

Thank you


texts: Why doesn't my 7 segment update every second like in the program?

texts:
I used sevseg.h library to write numbers to my 4 digit seven segment. The display should update every second with the current time since program started running. This is my code so far:

#include <SevSeg.h>

SevSeg sevseg;

void setup() {
    byte numDigits = 4;
    byte digitPins[] = {5, 4, 3, 2};
    byte segmentPins[] = {13, 12, 11, 10, 9, 8, 7, 6};
    sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(50);
    sevseg.setNumber(0000, -1);
}

void loop() {
    unsigned long timer = millis();
    for (int i = 0; i < 500; i++) {
        sevseg.setNumber(timer/1000, -1);
        sevseg.refreshDisplay();
        delay(2);
    }
}

Since the delay is 2, the for loop loops 500 times, resulting in 1000ms or 1 second. The current second is written to the display. For some reason, the display is updated every other 5 or 6 seconds. Why is this occurring? How can this be fixed so that my display turns into a stopwatch in a way?


texts: Assembly for loop repeating 2 times when it's only suppose to do it once

texts:
I'm programming an Arduino Nano so I belive that this question should be qualified for this SE.

I am trying to dim up an LED using a for loop in AVR assembly.

My problem is that the cycle is repeated twice before ending, while it is suppose to end after the first cycle.

A cycle is when the red_loop is repeated 256 times (to dim the led up). At that point, the value should overflow causing the variable to go back to 0. The code should stop there, but mysteriously, it does another cycle and then it stops.

Does anyone know why?

Here is my code :

.org 0x000

ldi r16, 0b111
out ddrb, r16

ldi r16, 0xff
out portb, r16

ldi r16, 0

; ff00 pin
; ff01 value
; ff02 led

ldi r16, 0b000
sts $ff00, r16

ldi r16, 0
sts $ff01, r16

red:
    ldi r16, 0b001
    sts $ff00, r16

red_loop:
    rcall pwm

    lds r16, $ff01
    inc r16
    sts $ff01, r16
    cpi r16, 0
    brne red_loop

end:
    rjmp end

pwm:
    ldi r24, 190

pwm_pre_loop:
    ldi r17, 0

pwm_loop:
    lds r16, $ff01
    cp r17, r16
    brge off

    cp r17, r16
    brlo on

pwm_loop_check:
    inc r17
    cpi r17, 0
    brne pwm_loop

    inc r24

    cpi r24, 0
    brne pwm_pre_loop

    ret

on:
    lds r16, $ff00

    sbrc r16, 0
    cbi portb, 0

    sbrc r16, 1
    cbi portb, 1

    sbrc r16, 2
    cbi portb, 2

    rjmp pwm_loop_check

off:
    lds r16, $ff00

    sbrc r16, 0
    sbi portb, 0

    sbrc r16, 1
    sbi portb, 1

    sbrc r16, 2
    sbi portb, 2

    rjmp pwm_loop_check


texts: Why is 'n' parameter of snprintf ignored?

texts:
I have found that the n parameter of snprintf() seems to be ignored in my code.

char asdf[10];
Serial1.println(snprintf(asdf, 2, "hello"));

This prints 5 when I would expect it to print 2. What is happening?


texts: First time arduino attempt. 4 switch inputs controlling 8 LED outputs

texts:
This is my first venture into Arduino. I am unsure which one to use even for this. As this will be a dedicated unit, and size is a small priority, the smaller the better.

Here is more info on the scheme I am looking for.

Switch 1 on turns on LED groups 1 and 2

Switch 2 on turns on LED groups 3, 4, 5, 6, 7 and 8

Switch 3 on turns on 1 for say 500 ms, then turns 1 off, turns on 3 for 500 ms, then turns off 3, then turns on 5 for 500 ms, then turns off 5, turns on 7 for 500 ms, then turns off 7, then loops back and turns on 1 repeating the cycle.

Switch 4 on turns on 2 for say 500 ms, then turns 2 off, turns on 4 for 500 ms, then turns off 4, then turns on 6 for 500 ms, then turns off 6, turns on 8 for 500 ms, then turns off 8, then loops back and turns on 2 repeating the cycle.

Will I need an Arduino uno, nano or micro?
I am hoping this will be an easy to do project in order to learn the world of Arduino


texts:
I have a few questions about the Arduino Micro circuit:

If I can provide a steady 5 V source (connected to +5V), then I don't need to use the voltage regulator module (including the selector) of the circuit. Correct?
If I can provide a steady 5 V source (connected to +5V), then I don't need to connect anything to VIN. Correct? If that's right, should I connect it (VIN) to GND, instead of leaving it floating?
If I'm not using +3.3V, should I connect it to GND (instead of leaving it floating)?
If I'm powering off of just USB, then I can connect +5V to VUSB. Correct?

Schematic below for reference:


texts: Using an Arduino to rotate a DC motor once a minute (edited)

texts:
I’m trying to write an arduino sketch that makes a dc motor turns one full rotation every 60s similar to a clock. The arduino will be connected to the gate of a typical mosfet and the dc motor will be connected to the drain of the mofset  such that the arduino controls the speed of the motor. Any suggestions on how I go about this?
I’m using an arduino mega 2560 in case that’s relevant.


texts: why leonardo bootloader is bigger than UNO?

texts:
Apparently leonardo and UNO are very similar boards.

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

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

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

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

Thanks!


texts: How to get the weather kit with anemometer working using arduino (UNO)?

texts:
I tried to build a weather station with anemometer and My setup is,
SwitchDoc Labs' anemometer kit (which is equivalent to sparkfun anemometer kit) connected to the grove weather-pi board with rtc clock DS3231 installed on which is connected to arduino UNO.

According to http://www.switchdoc.com/wp-content/uploads/2016/07/WeatherBoard_CurrentSpecification.pdf and their official tutorial https://www.switchdoc.com/2015/01/weather-arduino-weatherpiarduino/, if I use grove weather-pi board's JP2 connections to connect to the UNO/Mega2560 board then it suggests as following (in my case its UNO)

diagram 1
diagram 2

GroveWeatherPi_board    Mega        Uno     Units
    JP2/1 ->            A0          A0      WindVane
    JP2/2 ->            D2          D3      RainBucket
    JP2/3 ->            D5          D2      Anemometer
    JP2/4 ->            GND         GND     GND

And the supposedly working sketch/library is https://github.com/switchdoclabs/SDL_Weather_80422 which only compiles on arduino-IDE without issue if I use the fork https://github.com/soligen2010/Adafruit_ADS1X15 instead of the original https://github.com/adafruit/Adafruit_ADS1X15 with it but even then the wind-speed and wind-direction unit or to say the whole anemometer part just do not work or in other words, do not give any reading. I have tested the units individually up to the arduino pins with LED light on breadboard, they are sending signals/responding and also mounted the whole project on a Mega2560 as well but results remained unchanged.

I am assuming the pin-outs defined in the https://github.com/switchdoclabs/SDL_Weather_80422 are messed up then but how to redefine it in the sketch/library because in the ino sketch file, these are the pin-out definitions for primarily Mega2560

#define pinLED     13  // LED connected to digital pin 13
#define pinAnem    18  // Anenometer connected to pin 18 (not used in the diagram!) - Int 5 - Mega   / Uno pin 2
#define pinRain    2   // Anenometer connected to pin 2 - Int 0 - Mega   / Uno Pin 3
#define intAnem    5   // int 0 (check for Uno), according to the above two diagrams' comparison, for UNO this pin also goes to the pin 2
#define intRain    1   // int 1 (not used in the diagram! Then why? Its a TX pin)

Where the pinAnem and intAnem both indicates pin 2 for UNO according to the above two diagrams.

When I connect the I2C vcc pin from grove-weather-board to UNO's 5 volts instead of 3.3 volts as shown, the wind direction gets fixed but still no wind-speed reading.

So what are the corrections I need to do in the SDL_Weather_80422 library or in the connection diagram in this case?


texts: Unable to compile c++11 libraries despite having added -std=c++11 in platform.txt

texts:
I want to use c++ data structures such as vectors, arrays, map... in my Arduino sketch. I made sure to add -std=c++11 and -std=gnu++11 in platform.txt, I am still getting the following error message:

fatal error: unordered_map: No such file or directory
#include <unordered_map> compilation terminated. exit status 1 unordered_map: No such file or directory

Here's a snapshot from ~/arduino-nightly/hardware/arduino/avr/platform.txt:

Versions:

Arduino ide: 1.8.14
g++: 5.4.0
avr-g++: 4.9.2

What else should I set up?


texts: How can I swap a servo with a stepper motor?

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

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

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

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

This is a schematic of my project:

simulate this circuit – Schematic created using CircuitLab

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


texts:
Not sure if this is the right place to post this.

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 it just says there is an error downloading the files.

Is there a way to manually install the board support for the DUe, or must it be done automatically, connecting through the internet?

UPDATE

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.

UPDATE 2

Question has been answered:
https://github.com/arduino/Arduino/issues/3358

Many thanks to Federico Fissore!


texts:
I am currently working on a quadcopter in which I want help in setting up my PID.

I am trying to get output from the PID loop by giving input from MPU6050's (accelerometer and gyro) pitch value. The pitch value from the MPU6050 is given to PID loop, but I am not getting any output from the loop. I have set the setpoint as 0, and the output from the MPU6050 ranges between -90 to +90(this is the PID input).

My code for PID:

float input, output, setpoint=0;

PID* myPID(&input, &output, &setpoint, 2, 5, 1, REVERSE);

myPID.compute();

Then I am printing the output values but am getting only 0 whatever the input from MPU6050.


texts:
I can't appear to get my MKR1000 to list a port on my mac in the arduino ide, am i missing something obvious or does it need additional drivers?

Also
➜  ~  csrutil status
System Integrity Protection status: disabled.

running OSX 10.11.3

Board appears to be working, default led flashing


texts:
I'm using the arduino to generate a 100kHz pwd using timer 1

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

   // Timer 1 Fast PWM mode *toggling* OC1A at 50kHz with *two* OCR1A counts
   // And 7.32 bits 0-159 PWM on OC1B at 100kHz
   // Output on OC1B
   // Set at TOP, Clear at OCR1B
   // WGM =15 0b1111

   DDRB |= bit(DDB1) | bit(DDB2);  // atmega168/UNO OC1A and OC1B (Tested by OP/Luis)

   TCCR1A =  bit(WGM11) | bit(WGM10) | bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
   OCR1A  = 159 ;//79;    // Set TOP count to 16000000/(2*PreScaler*Ftoggle)
                          // or 16000000/(PreScaler *Ftimer)
   OCR1B  = 10;           // 10/160 duty cycle
   TCNT1 = 0 ;
}

void loop() {
  // put your main code here, to run repeatedly:
  OCR1B = 160/4 -1 ; // 25% duty cycle.
}

I used this to test the modules:

Receiver
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
int msg[1];
RF24 radio(9,10);
const uint64_t pipe = 0xE8E8F0F0E1LL;
int LED1 = 3;

void setup(void){
 Serial.begin(9600);
 radio.begin();
 radio.openReadingPipe(1,pipe);
 radio.startListening();
 pinMode(LED1, OUTPUT);}

void loop(void){
 if (radio.available()){
   bool done = false;
   while (!done){
     done = radio.read(msg, 1);
     Serial.println(msg[0]);
     if (msg[0] == 111){delay(10);digitalWrite(LED1, HIGH);}
     else {digitalWrite(LED1, LOW);}
     delay(100);}}
 else{Serial.println("No radio available");}}

Transmitter

#include  <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
int msg[1];
RF24 radio(9,10);
const uint64_t pipe = 0xE8E8F0F0E1LL;
int SW1 = 7;

void setup(void){
 Serial.begin(9600);
 radio.begin();
 radio.openWritingPipe(pipe);}

void loop(void){
 if (digitalRead(SW1) == HIGH){
 msg[0] = 111;
 radio.write(msg, 1);}}

I'm using this library
https://github.com/TMRh20/RF24

And it works ok, now first issue is that both, RF24 and the pwm
are using the pin 10 but the library allows you  to change it, so now I'm using pin 7 instead. I tested it again and still works fine.

But when I add the lines at the setup to use the pwd  the communication doesn't work

   DDRB |= bit(DDB1) | bit(DDB2);  // atmega168/UNO OC1A

   TCCR1A =  bit(WGM11) | bit(WGM10) | bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
   OCR1A  = 159 ;//79;    // Set TOP count to 16000000/(2*PreScaler*Ftoggle)
                          // or 16000000/(PreScaler *Ftimer)
   OCR1B  = 10;           // 10/160 duty cycle
   TCNT1 = 0 ;

I try line by line and the issue is here:

TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler

When setting the prescaler at 1.

Which is the dependency of the RF24 on this timer? and which options to I have to make it work

EDIT.

Now I'm using pins 6 and 7 for CE and CS
Also removed  "| bit(COM1A0) " form the register  setting

Still doesn't work

I've this

void setup(void)
{

  /// RF settings

  Serial.begin(9600);
 radio.begin();
 //radio.openReadingPipe(1,pipe);
 //radio.startListening();
 pinMode(LED1, OUTPUT);

 /// end RF settings

  //// pwd settings
 DDRB |= bit(DDB1) | bit(DDB2);
   OCR1A  = max_count;       // 16000000/(PreScaler *Ftimer)
   OCR1B  = 10;
   TCCR1A =  bit(WGM11) | bit(WGM10) |  bit(COM1B1); // bit(COM1A0) | Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
   TCNT1 = 0 ;

  ////
 }

If I put the settings for the PWM before the settings for the RF24 then the PWM doesn't work, the RF settings at first the the communications doesn't work.

radio.begin() must be overwriting the registers but I haven't found how.


texts: Breakpoints are a great way to see how the compiler runs to your code. Now my question is, is there a possibility to use breakpoints when you debug your code?


texts: Sending arduino sensor data via WiFi to a MySQL server

texts:
I'm aware this question has probably been asked many times but I'm pulling my hair out.
I'm trying to get sensor data from an arduino to a MySQL server. I've checked the apache access log and the request is there. But it just isn't being inserted into the database. Manually adding the data using the browser works so the php code seems fine. I've allowed apache through the firewall and updated the permissions all to no avail. Code below:
Arduino Main Code:
#include "thingProperties.h"
#include <Arduino_MKRENV.h>
#include <WiFi.h>

WiFiClient client;

void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
  delay(1500);

  //Connect to WiFi network
  int status = WL_IDLE_STATUS;
  while (status != WL_CONNECTED){
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(SSID);
    status = WiFi.begin(SSID, PASS);
    delay(10000);
  }
  Serial.println("This is connected.");

  if (!ENV.begin()) {
  Serial.println("Failed to initialize MKR ENV shield!");
  while(1);
  }
  pinMode(2, INPUT);
}

void loop() {
 relativeHumidity = int(ENV.readHumidity());
 lightIntensity = (ENV.readIlluminance());
 airPressure = int(ENV.readPressure(MILLIBAR));
 temperature = int(ENV.readTemperature());
 if(digitalRead(2) == LOW){
   rain = 1;
 }else if(digitalRead(2) == HIGH){
   rain = 0;
 }
 Serial.println("httpRequest");
 httpRequest();
 delay(10000);
}

void httpRequest(){
  // if there's a successful connection:
  if (client.connect(SERVER, 80)) {
    Serial.println("Connecting to server...");
    // send the HTTP PUT request:
    client.print("GET /weather_data.php?temp=");
    Serial.println("GET /weather_data.php?);
    client.print(temperature);
    client.print("&pressure=");
    client.print(airPressure);
    client.print("&humidity=");
    client.print(relativeHumidity);
    client.print("&illumination=");
    client.print(lightIntensity);
    client.print("&rain=");
    client.print(rain);
    client.print(" ");
    client.println("HTTP/1.1");
    client.print(" Host: ");
    client.println(SERVER);
    client.println();
    Serial.println("Added.");
  } else {
    Serial.println("Not connected.");
  }
  if (client.connected()){
    client.stop();
  }
}

thingProperties.h:
#include <WiFi.h>
#include <SPI.h>

const char THING_ID[] = "c942a18f-7696-4431-952c-76eaea3214ea";

const char SSID[]     = SECRET_SSID;    // Network SSID (name)
const char PASS[]     = SECRET_PASS;    // Network password (use for WPA, or use as key for WEP)
const char SERVER[]   = SECRET_IP;      // Server IP Address

int airPressure;
float lightIntensity;
float relativeHumidity;
bool rain;
float temperature;


texts: Adafruit Circuit Playground Express fails to upload

texts:
When uploading code to the Adafruit Circuit Playground Express, I have found that most of the time it fails to upload saying that the port is busy. There seems to be no logical reason behind this, as it uploads perfectly to an Arduino Uno (Yes, I did switch the board types). What am I doing wrong?
Here is the error:

processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:152)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:77)
    at processing.app.SketchController.upload(SketchController.java:732)
    at processing.app.SketchController.exportApplet(SketchController.java:703)
    at processing.app.Editor$UploadHandler.run(Editor.java:2075)
    at java.lang.Thread.run(Thread.java:748)
Caused by: processing.app.SerialException: Error touching serial port '/dev/ttyACM1'.
    at processing.app.Serial.touchForCDCReset(Serial.java:107)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:136)
    ... 5 more
Caused by: jssc.SerialPortException: Port name - /dev/ttyACM1; Method name - openPort(); Exception type - Port busy.
    at jssc.SerialPort.openPort(SerialPort.java:164)
    at processing.app.Serial.touchForCDCReset(Serial.java:101)
    ... 6 more

Operating system: kubuntu linux 64 bit

EDIT: Never mind. In the end I used chmod a-x /usr/sbin/ModemManager to remove execute permissions from every user, and that worked without any noticeable repercussions to my system. For anyone who wants to do the same, make note of the original permissions, so you can change it back if you have to.


texts: Any way to use DMA to transfer data to SD Card in ESP8266

texts:
I'm using ESP8266 at speed of 160 MHz to record ADC results into SD card, I need to do this at rate of 8 KHz. Means that i should save it on the SD Card or i'll run out of memory before 4 Sec passes.
I used timer1 to trigger sampling, but my problem is that surprisingly ESP8266 can not do this fast enough and the maximum sampling rate i get is about 7 KHz. I also tried to write data in ESP8266 Flash using littleFS in hope of acceleration but there was no luck. Here is my code:
#include <SPI.h>
#include <SD.h>

File dataFile;

int flag = 0;
int count = 0, level = 0, se_count = 0;

void inline analogReader() // Sampling and Recording processed which is done sequentially :(
{
  uint16_t dataByte = (uint16_t) analogRead(A0);
  dataFile.write((uint8_t*) &adcBuf, 2);

}

void ICACHE_RAM_ATTR onTimerISR() { // Timer sets the flag every 0.125 MS
  flag = 1;
}

void setup() {
  pinMode(A0, INPUT);
  pinMode(D0, OUTPUT);

  Serial.begin(115200);

  if (!SD.begin(D0)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");

  File root = SD.open("/");

  if (SD.exists("real_test.bin"))
  {
    SD.remove("real_test.bin");
  }

  dataFile = SD.open("real_test.bin", FILE_WRITE);

  if (dataFile) {
    Serial.println("File created!");
  }
  else
  {
    Serial.println("Failed to create file!");
    return;
  }

  // Setting the timer so that timer interrupt fires every 0.125 MS
  timer1_attachInterrupt(onTimerISR);
  timer1_enable(TIM_DIV1/*from 80 Mhz*/, TIM_EDGE/*TIM_LEVEL*/, TIM_LOOP/*TIM_SINGLE*/);
  timer1_write(10000); /* ( 80 / 1 ) * 125 */
}

void loop() {
  if (flag) // To check whether its time to sampling or not, because of the low speed of the process
  {         // The flag is set again before one iteration ends.
    flag = 0;

    if (se_count < 10)
      analogReader();

    count++;
    if (count == 8000) // When 8000 sample & write process done notify using serial monitor. (it is
                          always more that 1 Sec. for example 1.3 Sec.)
    {
      count = 0;
      level = !level;
      Serial.println(level);

      se_count++;
      if (se_count == 10) // When we done 8000 * 10 sample & write we close the file. it supposed to
                          // be done in almost 10 sec. but it takes more time in practice. for
                          // example 13 Sec.
      {
        dataFile.close();
        Serial.println("Write ended");
      }
    }

  }
}

I even used a faster method system_adc_read_fast(buf, num, clk_div) that is available in ESP-SDK, So i'm desperately seeking for one or two of approaches bellow if possible:

To use a non-blocking approach: If there is any possibility to hand SD writing to DMA so that i only fill the ADC buffer for DMA, or an interrupt for ADC complete so that i write to SD and when interrupt fired put the result in the buffer and return back to SD writing.
Yet faster approach for both ADC sampling and writing: Can i increase the SD write speed of SD library? for example by configuring SPI for maximum speed rate.

I also tried SDFat library but it does not recognize my SD Card. The whole process is odd to me that even by using a 160 MHz CPU and hardware i can not record ADC data at rate of 8000 Sample/S. I have TIME limitation so please help me.
Any suggestion is appreciated. Thanks in advance.


texts: Data type explanation regarding analogRead of a photoresistor

texts: This is a fundamental question - very new (1st post) and trying to learn.  I have a photocell connected in series with a 10kOhm resistor between 5v & Gnd (to make a voltage divider) and the divided voltage is connected to A1.  In my code, when I specify the datatype as uint8_t I get values around the 200 range, yet when I change the type to uint16_t the values change to 1000 range.  Where should I be looking to understand this behavior?


texts: AVR & PIC 8-bit Microcontrollers - Can you add: external flash memory, external RAM, video & audio output, more address busses?

texts:
so I was planning on creating a mini PC out of basic ICs and 8-bit microcontrollers such as ATTinys and/or PICs and I have several questions regarding those:

Can you add external RAM, say with SRAM, DRAM chips, so the microcontroller can handle larger programs? (ones requiring more memory to be executed). I've seen an excellent discussion here: External Flash Memory for ATtiny85, which exclaims that I can't do that with AVRs (but why exactly is that? What about PICs, or any 8-bit uCs for that matter).
Can you add external memory, like flash or EEPROM, so that the microcontroller can store some files (sort of a hard drive (but more like an SSD I guess).
Also, how would you go around connecting memory chips together to get more memory out of them? Would there be a difference with memory chips like serial flash and parallel flash?
Can you use them to output and create basic audio & output HDMI? (or communicate with external ICs to do that task)
Can you somehow connect say 2 8-bit ATTinys to get a pseudo 16-bit microcontroller? Would that mean they could process more data at the same time?

Thanks,
some guy on the internet.


texts: C++ Undefined reference to 'Class:Function()'

texts:
I have these files:

Project.ino
Sensor.h
Sensor.cpp
IMU/L3G.h
IMU/L3G.cpp

Sensor.h

#ifndef Sensor_h
#define Sensor_h

#include <EEPROM.h>
#include "IMU/L3G.h"

#define CUTOFF_FREQ 30
#define FREQ 400

class Sensor {
public:
    Sensor();
    ~Sensor();
    void Init(void);

pivate:
    L3G gyro;
};
#endif

Sensor.cpp

#include "Sensor.h"

Sensor::Sensor()
{

}
Sensor::~Sensor()
{

}

void Sensor::Init(void)
{
  if (!gyro.init())
  {
    Serial.println("Failed to autodetect gyro type!");
    while (1);
  }
  gyro.enableDefault();
}

Project.ino

#include <i2c_t3.h>
#include <EEPROM.h>
#include <Servo.h>
#include "Sensor.h"

Sensor sensor = Sensor();

void setup() {

  sensor.Init();
}

I got this error

/var/folders/8q/rbt7zf3d28b3k9t6d24k5sn00000gn/T/arduino_build_748953/sketch/Sensor.cpp.o: In function `Sensor::Init()':
/var/folders/8q/rbt7zf3d28b3k9t6d24k5sn00000gn/T/arduino_build_748953/sketch/Sensor.cpp:15: undefined reference to `L3G::init(unsigned char, unsigned char)'
/var/folders/8q/rbt7zf3d28b3k9t6d24k5sn00000gn/T/arduino_build_748953/sketch/Sensor.cpp:20: undefined reference to `L3G::enableDefault()'

So, what is wrong?


texts:
Hello guys, this is my code and I am basically doing if-else statement.

int led = D2;
int but = D1;

void setup() {
  pinMode(led, OUTPUT);
  pinMode(but, INPUT);

}

void loop() {
  if (digitalRead(but) == HIGH){
    digitalWrite(led, HIGH);
  }else{
    digitalWrite(led, LOW);
  }

}

I have also attached the photo so that you can diagnose the situation.

The led show only glow if the button is pressed. But the led keeps glowing for longer time and I don't know why.
I think there is current leak somewhere in the circuit or the internal processing is slow.
Please help me guys.


texts: How would I refactor this code, given how similar most of the lines are?

texts:
I have a set of buttons and a set of NeoPixel LEDs. There's lots of very similar constants (button1pin, button2pin, etc) so there's almost certainly a more efficient way of coding this.

Any ideas?

#include <Adafruit_NeoPixel.h>
Adafruit_NeoPixel strip = Adafruit_NeoPixel(9, 2, NEO_RGBW + NEO_KHZ800);

// Buttons
const int button1pin = 3;
const int button2pin = 4;
const int button3pin = 5;
const int button4pin = 6;
const int button5pin = 7;
const int button6pin = 8;
const int button7pin = 9;
const int button8pin = 10;
const int button9pin = 11;

const int led1 = 0;
const int led2 = 1;
const int led3 = 2;
const int led4 = 3;
const int led5 = 4;
const int led6 = 5;
const int led7 = 6;
const int led8 = 7;
const int led9 = 8;

void setup() {
  strip.begin();
  strip.show();

  pinMode(button1pin, INPUT_PULLUP);
  pinMode(button2pin, INPUT_PULLUP);
  pinMode(button3pin, INPUT_PULLUP);
  pinMode(button4pin, INPUT_PULLUP);
  pinMode(button5pin, INPUT_PULLUP);
  pinMode(button6pin, INPUT_PULLUP);
  pinMode(button7pin, INPUT_PULLUP);
  pinMode(button8pin, INPUT_PULLUP);
  pinMode(button9pin, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(button1pin) == LOW){
    strip.setPixelColor(led1, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button2pin) == LOW){
    strip.setPixelColor(led2, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button3pin) == LOW){
    strip.setPixelColor(led3, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button4pin) == LOW){
    strip.setPixelColor(led4, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button5pin) == LOW){
    strip.setPixelColor(led5, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button6pin) == LOW){
    strip.setPixelColor(led6, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button7pin) == LOW){
    strip.setPixelColor(led7, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button8pin) == LOW){
    strip.setPixelColor(led8, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button9pin) == LOW){
    strip.setPixelColor(led9, strip.Color(20, 55, 0, 0));
  }

  strip.show();
}


texts: RFM95 digital io to control mute on PAM8403 to get rid of hiss while receiving

texts:
I am building a solution with an ESP32, a PAM8403 amp, a parallel TFT display, and a RFM95 LoRa module. All works great but I want to get rid of the noise that is generated when Lora is in receive mode.
I can do this by pulling pin 12 low on the PAM8403, which mutes all sound. However I have ran out of output pins on my ESP32, and it's too late to use a IO expander as the PCB has been built.
My initial idea was to use the RX/TX pins on the ESP32 when the unit was out of diagnostics mode. However if I can avoid this then that would be great. In my code when I issue Lora.sleep() / Lora.idle() the hissing goes away.
So I started to wonder if I could just trigger the mute function through another logic state that goes low when LoRa is idle and high when sleeping (allowing the mute to deactivate).
I am using the LoRa library by Sandeep Mistry, and I was wondering if I could use DIO1, DIO2, etc. as an IO PIN to control mute. If not, is it possible to use any of the already connected pins to behave in the desired way?
Thanks all in advance!


texts:
The goal for this is to create a struct that includes a name, ID, fileName, and a boolean, then create an array of that structs.
Here's what I came up with:
struct Amiibo
{
  char *aName{};
  char *ID{};
  char *AudioFileName{};
  bool alreadyPlayed{false};
};

Amiibo amii[20] = {

      {"Mario","A5005B00","MARIO",false},                     //0
      {"Meta Knight","A5 00 02 00","MK"},                     //1
      {"Inkling", "A5 00 05 00","INK"},                       //2
      {"Donkey Kong","A5 00 01 00","DK"},                     //3
      {"Lucas","A5 00 0A 00","LUCAS"},                        //4
      {"Duck Hunt", "A5 00 08 00","DUCKH"},                   //5
      {"Ocarina of Time Link","A5 00 01 00","OOTL"},          //6
      {"Breath of The Wild Link","random","BOTWL"},           //7
      {"8-bit Link","random","8BITL"},                        //8
      {"Toon Link","random","TOONL"},                         //9
      {"Mr. Game and Watch","random","GANDW"},                //10
      {"Falco","random","FALCO"},                             //11
      {"King Dedede","random","DEDEDE"},                      //12
      {"Mewtwo","random","MEWTWO"},                           //13
      {"Captain Falcon","random","CAPF"},                     //14
      {"ROB","random","ROB"},                                 //15
      {"PAC-MAN","random","PACMAN"},                          //16
      {"Cloud","random","CLOUD"},                             //17
      {"Ness","random","NESS"},                               //18
      {"Ryu","random","RYU"}                                  //19

};

This gives me the following error:

error: could not convert '{"Mario", "A5005B00", "MARIO", false}' from '' to 'Amiibo'

And the same error for all the other elements of the array.
I tried changing amii[20] to a pointer using *amii[20]. That got me this error:

braces around scalar intializer for type "Amiibo"

I'm not sure what to make of that, since I'm fairly certain this isn't scalar type.
I'd really just like to make a struct array so I can cycle through these at random using a random seed. It shouldn't be that difficult, yet I'm running up against a wall. I'd appreciate any advice you all have to give. Thanks.


texts: Cannot correctly access element in array when given index

texts:
I have the following strings which are stored in the program memory. They are basically just morse code definitions, with another array of characters where each character in the array has the same index as the morse code definitions:

const char a[] PROGMEM = ".-";
const char b[] PROGMEM = "-...";
const char c[] PROGMEM = "-.-.";
const char d[] PROGMEM = "-..";
const char e[] PROGMEM = ".";
const char f[] PROGMEM = "..-.";
const char g[] PROGMEM = "--.";
const char h[] PROGMEM = "....";
const char i[] PROGMEM = "..";
const char j[] PROGMEM = ".---";
const char k[] PROGMEM = "-.-";
const char l[] PROGMEM = ".-..";
const char m[] PROGMEM = "--";
const char n[] PROGMEM = "-.";
const char o[] PROGMEM = "---";
const char p[] PROGMEM = ".--.";
const char q[] PROGMEM = "--.-";
const char r[] PROGMEM = ".-.";
const char s[] PROGMEM = "...";
const char t[] PROGMEM = "-";
const char u[] PROGMEM = "..-";
const char v[] PROGMEM = "...-";
const char w[] PROGMEM = ".--";
const char x[] PROGMEM = "-..-";
const char y[] PROGMEM = "-.--";
const char z[] PROGMEM = "--..";
const char one[] PROGMEM = ".----";
const char two[] PROGMEM = "..---";
const char three[] PROGMEM = "...--";
const char four[] PROGMEM = "....-";
const char five[] PROGMEM = ".....";
const char six[] PROGMEM = "-....";
const char seven[] PROGMEM = "--...";
const char eight[] PROGMEM = "---..";
const char nine[] PROGMEM = "----.";
const char zero[] PROGMEM = "-----";

const char* const morse_table[] PROGMEM = {a, b, c, d, e, f, g, h, i, j, k, l, m,
    n, o, p, q, r, s, t, u, v, x, y, z, one, two, three, four, five, six,
    seven, eight, nine, zero};

const char alphabet[] PROGMEM = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0'};

I am then creating a function which is supposed to be able to take in the morse code definition and spit out a character. This function is below:

void checkString(char * compare) {
  //Unwrap the pointer to the array into a "real" array
  char buf[7];
  for (int i = 0; i < 6; i++) {
    buf[i] = compare[i];
  }

  int correctIndex = -1;

  for (int iterator = 0; iterator < 35; iterator++) {

    char buf2[7];
    strcpy_P(buf2, (char*)pgm_read_word(&(morse_table[iterator])));

    if ((buf[0] == buf2[0]) && (buf[1] == buf2[1]) && (buf[2] == buf2[2]) && (buf[3] == buf2[3]) && (buf[4] == buf2[4])) {
      correctIndex = iterator;
    }
  }

  if (correctIndex == -1) {
    Serial.println("Failed!");
  }

  else {
    Serial.print("Success! Index: ");
    Serial.println(correctIndex);
  }

  char characterBuffer = alphabet[correctIndex];
  Serial.println(alphabet[correctIndex]);
}

The strcpy_p line of code was essentially copied from the PROGMEM reference for Arduino. I don't understand much about it, but from my tests it appears to work in getting an actual string object out of the pointer.

If I input any of the morse code definitions given, the correctIndex integer does contain the correct location of that definition in the morse_table 2d array. However, when I pass this integer into the alphabet array hoping to get out the character at that location I am given a seemingly random character. Is there something that I'm doing wrong with this code to produce such a result? Thanks for your help.


texts: Issues converting an uint32_t into a char*

texts:
I'm using a capacitive touch sensor that as 12 touch points and stores it's state data as a binary number.

I want to take that state, add a bit of data onto the front, and then send it up to a server via websockets. I'm using the Arduino Websockets library for my websocket client.
The library has a sendBinary method that allows you to provide a character pointer for the data.

So, I wrote a function that makes a new 32 bit unsigned integer, adds my metadata, then the touch state, and then attempts to take the address of the payload integer and cast it to a character pointer:
void sendTouchStateToServer()
{
    Serial.println("sending state to server");

    uint32_t payload = touchControllerMessageType << 12;
    Serial.println(payload);
    payload |= currentTouchState;

    Serial.print("Payload contents: ");
    Serial.println(payload);
    Serial.print("Payload contents cast as character pointer: ");
    Serial.println((char *)&payload);
    Serial.print("Payload size: ");
    Serial.println(sizeof(payload));

    client.sendBinary((char *)&payload, sizeof(payload));
}

The issue is that while the integer version of the payload looks fine, when I try to cast it into a character pointer the contents is wrong.

I've also tried creating a payloadPointer and directly set the address of the integer as the pointer address, but this also fails.

(I should take this moment to say I'm still pretty green to arduino cpp concepts like this).
What's the right way of doing this? I'm reading up on pointers and trying to understand how to properly do it, but I can't quite figure it out. Could someone explain the correct way of doing it and why? I want this to work, but more than that I want to understand the "why and how" of the proper way.
Thanks! :bows:


texts:
In my project I have an issue. I have more than 2 mesh network with Arduino + nRF240L01 with a star topology (one Arduino is master another 6 Arduino + nRF240L01 are the slaves likewise I can be able to have more than 2 networks).

So I want to communicate only with one mesh network but not to another. Is the different addressing enough to separate the networks? And I would like to have sample code as well.


texts: Arduino MKR Zero problem with new UART comunication

texts:
I'm currently using an Arduino MKR Zero board and I need to add a new communication because the Serial1 on pins 13 and 14 is already used by another device.

I've followed this tutorial from Arduino official website to create a new serial communication, but using the given code I have no communication on pins 0 and 1.

The code compiles, but it doesn't work when uploaded to the MKR Zero board.
I've noted that IrqHandler() is not highlighted in my Arduino IDE (it remains black).

So, should I install some library?

Thank you.


texts: How do I Read and Write data from a USB stick?

texts: Hello I have an Arduino Uno and I salvaged a USB port from an old computer. The USB port has 4 pins on it and it accepts USB sticks. I was wondering if it is possible to connect it to my Arduino so my Arduino can load data from files on the USB. I don't want to go out and buy a shield but I don't mind using libraries. Is it possible to read and write data from a USB stick with Arduino?


texts:
I am totally new to and don't know where to start, I am interested in building new system with combination of hardware and software and every time I search how to make that embedded system it finally reaches to Arduino and don't know anything about that what to buy and I also have some more question like

Is one Arduino device required for each Arduino project ?
Should I have to buy more then one device for each project ?
If not then how I will make that project run without Arduino ?


texts:
I make my own library for arduino.

The file structure is like below.

AAA - README.md
    - examples - A - A.ino
               - B - B.ino
    - AAA.h
    - BBB.h
    - CCC.h
    - BBB.cpp
    - CCC.cpp

It works well. But I want to grouping a library source files like below.

AAA - same as above
    - src - AAA.h
          - BBB.h
          - CCC.h
          - BBB.cpp
          - CCC.cpp

It doesn't work at all.

Arduino IDE shows the message

  Specified folder/zip file does not contain a valid library.

But, WiFi101 library was made by src folder. Why isn't it possible for mine?


texts: Connect 9 V battery to Arduino Mega 2560 directly?

texts: Is it safe to connect a 9 volt battery to an Arduino Mega 2560 directly to power it?


texts: HC-05 with ELM327 mini OBD2 Bluetooth adapter connection problem

texts:
I am using Arduino Uno and HC05 Zs-040 Bluetooth module to establish a connection with ELM327 mini OBDII Bluetooth adaptor.

I have tried more than 15 different sequences of AT commands and most of them works successfully and HC05 reply with "ok" with no errors.

When I switch off the power from the HC05 and reconnect it again to connect automatically to the MAC address stored in it during configuration, the HC05 connects to the ELM327 OBDII adaptor for a time interval ranges from 2 to 5 seconds then the connection is lost.

I was able to notice that from the LED blinking on the HC05. This process of connection and disconnection is repeated automatically and the LED on the HC05 blinks in different patterns.

Also, I was able to connect to the ELM327 OBDII adaptor using a python script and it connects to it (I did that at the same time when the HC05 was trying to connect to OBDII adaptor which confirms that the connection between HC05 and the adaptor was not established).

In addition, I was able to connect to ELM 327 adaptor using Torque application and Bluetooth terminal application and both work fine.

Can anyone help me figuring out why does the connection is lost as soon as it is established?


texts: Please help with my tinkercad code. Debouncing stopwatch with lcd

texts:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int ssPin = 8;
int resetPin = 9;

bool cntrRunning = false;

int sec = 0;
int min = 0;
double currentMillis;

void setup()
{
    Serial.begin(9600);
    lcd.begin(16, 2);
    lcd.print("00:00");
    pinMode(ssPin, INPUT);
    pinMode(resetPin, INPUT);
}

void loop()
{
    if (digitalRead(ssPin) == HIGH)
    {
        if (cntrRunning)
        {
            stop();
        }
        else
        {
            start();
        }
    }
    else
    {
        if (cntrRunning)
        {
            keepRunning();
        }
        else
        {
            stop();
        }
    }

    if (digitalRead(resetPin) == HIGH)
    {
        if (cntrRunning)
        {
            stop();
            reset();
        }
        else
        {
            reset();
        }
    }
    delay(10);
}

void start()
{
    currentMillis = millis();
    cntrRunning = true;
    Serial.println("started");
}

void keepRunning()
{
    cntrRunning = true;

    if ((millis() - currentMillis) >= 1000)
    {
        sec++;
        currentMillis = millis();
        Serial.println(sec);

        if (sec < 10)
        {
            lcd.setCursor(4,0);
            lcd.print(sec);
        }
        else if (sec == 60)
        {
            min++;
            sec = 0;
            lcd.setCursor(3,0);
            lcd.print("00");
        }
        else
        {
            lcd.setCursor(3,0);
            lcd.print(sec);
        }

        if (min < 10)
        {
            lcd.setCursor(1,0);
            lcd.print(min);
        }
        else if (min == 60)
        {
            min = 0;
            lcd.setCursor(0,0);
            lcd.print("00");
        }
        else
        {
            lcd.setCursor(0,0);
            lcd.print(min);
        }
    }
}

void stop()
{
    cntrRunning = false;
    Serial.println("stopped");
}

void reset()
{
    if (cntrRunning)
    {
        stop();
    }
    reset();
    int sec=0;
    int min=0;
}

My professor wants us to add debouncing to the set/stop button but I'm a little confused on how to implement it.


texts: For which type of serial communication is Arduino Severino designed?

texts:
Arduino has become quite costly where I come from (2/3 of the price of Raspberry PI) so I have created an Arduino Severino clone.

I had used the device with the RS-232 Usb-Serial converter. But after a (long) while, the device stopped working. My friend came up with a point that RS-232 communication ranges between +6 to -6 V (with thresholds at +3 and -3 volts).

So I have tried FT232 which uses 0 to 5 volts instead. I have a little Chinese FTDI chip designed to do that:

However, after connecting it, it behaves unexpectedly. (it had crashed my PC, one of the communication LEDs is on all the time...) I realised that the Arduino board might get broken for a different reason (an accidental short-circuit is very likely).

So for which type of communication is this "Arduino" designed?


texts:
the project i'm working on is a weather station out door and for that i need to to give arduino at least some sort of protection from moisture.

https://www.instructables.com/id/Arduino-Weather-Station-AWS/

putting arduino in a box might work but the humidity where i live is very high it's rain a lot but the cold is not much. looking for ideas to waterproof arduino board please.

also can arduino work everyday of year without problem?


texts:
I'm facing this compilation issue.

Arduino: 1.8.4 (Linux), Board: "Intel® Edison"

fork/exec /home/jimish/.arduino15/packages/Intel/tools/core2-32-poky-linux/1.6.2+1.0/i686/sysroots/pokysdk/usr/bin/i586-poky-linux/i586-poky-linux-g++: no such file or directory
Error compiling for board Intel® Edison.

Arduino IDE:

Web IDE:


texts:
I have been trying to upload a simpley software code to my nodemcu arduino, but i keep getting this error :

exec: "C:\Users\jean-claude\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++": file does not exist
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

1.8.5 (Windows 10), Board _NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)

Does anybody know what can I do to solve this problem ??


texts:
I am completely new to programming and I am trying a brute force programming on my garage door opener. I want to use an Arduino for learning purposes. I wrote the following program that finally did what it should and now I am wondering whether there is a shorter code that does the same. Is anyone able to help me in that matter?

I do know that about 2^12 possibilities existed so I ran through all of them. I also knew that some parts of the "pulsetrain" (the set of necessary pulses) start with a particular sequence that is always the same (for all "brute forced" trains) and that the closing sequence is also always identical. I then simply wrote that down in the following, nasty code:

/*
  Transmitter is connected to Arduino Pin #2
*/

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

void pulsetrain(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m) {
  PORTD &= ~_BV(PD2);
  //set to LOW, hardwired to make it faster, see http://www.instructables.com/id/Arduino-is-Slow-and-how-to-fix-it/?ALLSTEPS
  delayMicroseconds(283); // (D2)
  PORTD |= _BV(PD2); //set to HIGH
  delayMicroseconds(566);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(283);
  PORTD |= _BV(PD2);
  delayMicroseconds(566);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(a);
  PORTD |= _BV(PD2);
  delayMicroseconds(b);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(c);
  PORTD |= _BV(PD2);
  delayMicroseconds(d);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(e);
  PORTD |= _BV(PD2);
  delayMicroseconds(f);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(g);
  PORTD |= _BV(PD2);
  delayMicroseconds(h);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(i);
  PORTD |= _BV(PD2);
  delayMicroseconds(j);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(k);
  PORTD |= _BV(PD2);
  delayMicroseconds(l);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(m);
  PORTD |= _BV(PD2);
  delayMicroseconds(283);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(566);
  PORTD |= _BV(PD2);
  delayMicroseconds(283);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(566);
  PORTD &= ~_BV(PD2); // last LOW
}

void loop() {
  int signals[2] = {283, 566};
  for (int a = 0; a < 2;  a++) {
    for (int b = 0; b < 2;  b++) {
      for (int c = 0; c < 2;  c++) {
        for (int d = 0; d < 2;  d++) {
          for (int e = 0; e < 2;  e++) {
            for (int f = 0; f < 2;  f++) {
              for (int g = 0; g < 2;  g++) {
                for (int h = 0; h < 2;  h++) {
                  for (int i = 0; i < 2;  i++) {
                    for (int j = 0; j < 2;  j++) {
                      for (int k = 0; k < 2;  k++) {
                        for (int l = 0; l < 2;  l++) {
                          for (int m = 0; m < 2;  m++) {
                            pulsetrain(signals[a], signals[b], signals[c], signals[d], signals[e], signals[f], signals[g], signals[h], signals[i], signals[j], signals[k], signals[l], signals[m]);
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}