texts: Arduino timer to turn a serve at a certain time

texts:
i am working on a project for my school tech class. Our goal is to make a vehicle that will travel along a cable and drop an egg to a target while going down the cable. i am using an arduino to to open a trap door with a servo after a certain amount of time that is set by two push buttons, and a third push button will control when the timer starts.
Here is my circuit

Here is the code:

#include <Servo.h>
#include <LiquidCrystal.h>

int b = 0;
int up = 0;
int down = 0;
int val = 100;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

Servo myservo;

int pos = 0;

void setup()
{
  pinMode(b, INPUT);
  pinMode(up, INPUT);
  pinMode(down, INPUT);
  lcd.begin(16, 2);
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  digitalRead(down);
  digitalRead(up);
  digitalRead(b);
  lcd.setCursor(0, 0);
  lcd.print("milli seconds:");

  while (b == HIGH)
  {
    digitalRead(down);
    digitalRead(up);
    digitalRead(b);
    lcd.setCursor(0, 1);
    lcd.print(val);
    myservo.write(0);
    if (up == HIGH, down == LOW)
    {
      val + 1;
    }
    if (down == HIGH, up == LOW )
    {
      val - 1;
    }

    delay(val);
    myservo.write(100);
    delay(1000);
  }
}


texts: How can I measure if a battery is there?

texts:
With my arduino I want to measure if one / two AAA batteries are in their single / double battery holder.

When the Arduino is running, connected to some other power supply and the batteries are in place everything is fine: I get my measurements of around 1.5V / 3V on the analog pin the battery is connected to (- of battery and Arduino GND are connected as well of course).

Problems arise when I either

a) pull the batteries out: The analog pin is left floating. Not good. Can I put the pin into INPUT_PULLUP mode? Is the internal resistor big enough? Or will the then connected 5V damage my batteries when they are back in the battery holder?

b) dissconect the Arduino from its external power supply: Because the Arduino is then "powered" by the 3V through the analog pin my blinking LED keeps blinking (at less brightness, but still...). I neither want the batteries to get drained nor damage my Arduino with it. So I would like to avoid this.

Actually I don't care about the actual battery voltage - I just want to know if the batteries are in their holder or not. And I want to leave the batteries there even though the Arduino is not powered. I would even consider something like "a button is held down when a battery is in its holder" or any other (simple) creative ideas.

Is this possible? How?


texts: Is it possible for the Arduino's digital pin mode to flip from OUTPUT to INPUT unexpectedly?

texts:
I have an Arduino project (data logger intended to sample 100 samples per second for months) with firmware that is too long to post. It mostly works as supposed to, but I have a confusing issue I can't figure out: rarely, the indicator LEDs (driven by digital pins) stop working. By rarely, I mean if I run 20 devices for two weeks, maybe one will develop the issue, so it's very hard to test empirically but it's frequent enough that it matters. I know it's not a hardware problem because they start again after a reset. The device apparently continues working fine apart from the LED issue when this happens.
I have three hypotheses:

There's a logic problem in my firmware code. I'm skeptical because the relevant block of code is pretty simple.
A memory overflow or some similar problem causes the program to fail at this one particular task but not others. I'm a little skeptical because the device reports free stack in the metadata every second and it's always over 40 bytes; I may be misunderstanding memory use though.
Somehow, the digital pin (4) driving the LED gets flipped from OUTPUT to INPUT. There's definitely no pinMode(4, INPUT) command anywhere in my code though, so if this is happening it's not my code doing it.

Let's suppose it isn't #1. Considering #2: is it likely that a weird memory issue is causing a very specific failure while not affecting core functions of the device?
Considering #3, is there anyway the register setting a pin to INPUT or OUTPUT could be flipped unexpectedly? It sounds crazy to me but I want to rule it out.
The platform is similar to the Arduino Pro (3.3V, 8 MHz, ATMEGA328p) and I'm running the current IDE version (1.8.13). Thanks for any help.


texts:
I'm pretty sure that this is the right forum to ask this question, but if it's not just lmk.

I am trying to create an auto clicker that is as hidden as possible for a computer engineering HID unit project.

What I have created so far (it works) is an Arduino being sent serial data via a C++ application that when receives a  '@' character triggers the auto clicker code and a '#' to stop the clicking. I showed my teacher and he said this is too basic as it's just simply a serial data sending application, but he likes the autoclicking idea.

I had a few ideas but I don't know how I would make them work. All I am trying to do is while a keyboard or mouse button the arduino sends mouse clicks.

TLDR; Is there a way that I can communicate keyboard or mouse events from the mouse/keyboard directly to the Arduino whilst still working normally on the computer itself, or maybe even something less discrete like making a device driver?

I suck at coding btw so I will most likely need someone I know to help me code it.


texts: Unable to set up Intel Edison on Windows

texts:
I am new to hobby electronics and have hit a dead end with my Intel Edison (which hopefully will not join the pile of useless components I have wasted my money on), and would appreciate some help with the setup procedure. The main problem is that I cannot connect to my Edison via the middle (lets call it "A") micro-USB port in order to get it into a working condition.

My objective is to connect to it's build-in Linux via SSH with the USB cables connected after installing the latest flash image.

I am using an Edison with an Arduino breakout board.

Here is the sequence of steps I followed:

I connected a 12V 2.6A AC to DC adapter to power the board. (Via the barrel connector). The green light came on to indicate it is powered.
I connected the "A" micro-USB port (i.e. not the one on the edge) to my computer.

At this point I could access the drive through Windows Explorer, however this changed when I executed the next step:

I installed the software from step 2 at https://software.intel.com/en-us/iot/library/edison-getting-started.
Something went wrong during the subsequent installation process. I don't know what.

At this point I could no longer access the drive. It would only appear as an "Unknown device" in Windows Device Manager. In order to try and fix this I gave up on the option where it is mounted as a Windows Drive.

I connected to the micro-USB port at the edge of the Arduino board and disconnected A.
I went to Windows Device Manager and found the connected device on COM6
I installed Putty and connected to COM6 with a baud of 115200.
The console showed a blank screen with a green cursor in the top left.
I waited 30 seconds for it to boot.
I hit Cntrl+C because I still saw the same screen from step 9.

I then saw this on the console:

Unknown boot mode: boot
Saving Environment to MMC...
Writing to MMC(0)... done
Resetting to default boot mode and reboot...
resetting ...

******************************
PSH KERNEL VERSION: b0182b2b
                WR: 20104000
******************************

SCU IPC: 0x800000d0  0xfffce92c

PSH miaHOB version: TNG.B0.VVBD.0000000c

microkernel built 11:24:08 Feb  5 2015

******* PSH loader *******
PCM page cache size = 192 KB
Cache Constraint = 0 Pages
Arming IPC driver ..
Adding page store pool ..
PagestoreAddr(IMR Start Address) = 0x04899000
pageStoreSize(IMR Size)          = 0x00080000

*** Ready to receive application ***

U-Boot 2014.04 (Jun 19 2015 - 12:05:55)

       Watchdog enabled
DRAM:  980.6 MiB
MMC:   tangier_sdhci: 0
In:    serial
Out:   serial
Err:   serial
Hit any key to stop autoboot:  0
Target:ifwi
Partitioning already done...
Partitioning already done...
Saving Environment to MMC...
Writing to redundant MMC(0)... done
GADGET DRIVER: usb_dnl_dfu

I have no idea what to do next.


texts: Optimizing code to use less Flash Memory and SRAM

texts:
I'm trying to reduce my sketch size and managed to reduce both SRAM and Flash memory.

From:
1570 SRAM - 32144 Flash memory
To:
644  SRAM - 19458 Flash memory

This are what I've done so far:

✓ Enabling LTO

✓ Using PROGMEM

✓ Dropping string and using char

✓ Dropping bootloader

✓ Using port manipulation

✓ Using registers to declare pins output/input

✓ Removing/Optimizing/Combining; unnecessary/repeated codes in the sketch

Using EEPROM is not an option for me.

What else i can do to take optimization one or two step further?


texts: How to make the motor car move left-forward / left-backward/ right-forward/ right-backward

texts:
I'm using an Arduino Uno to make a motor car. And I successfully made it move forward / backward / left / right.

void forward(void) {
  analogWrite(EA, 254); //speed 0 - 255
  analogWrite(EB, 255); //speed 0 - 255
  digitalWrite(EN2, LOW);
  digitalWrite(EN3, HIGH);
  digitalWrite(EN4, LOW);
  digitalWrite(EN5, HIGH);
}

void backward(void) {
  analogWrite(EA, 255); //speed 0 - 255
  analogWrite(EB, 255); //speed 0 - 255
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, LOW);
  digitalWrite(EN4, HIGH);
  digitalWrite(EN5, LOW);
}

void left(void) {
  analogWrite(EA, 180); //speed 0 - 255
  analogWrite(EB, 180); //speed 0 - 255
  digitalWrite(EN2, LOW);
  digitalWrite(EN3, HIGH);
  digitalWrite(EN4, HIGH);
  digitalWrite(EN5, LOW);
}

void right(void) {
  analogWrite(EA, 180); //speed 0 - 255
  analogWrite(EB, 180); //speed 0 - 255
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, LOW);
  digitalWrite(EN4, LOW);
  digitalWrite(EN5, HIGH);
}

The problem is, I found it is quite strange if I need to first press left/ right and press forward to turn around. I would like to make 4 extra buttons for left-forward / left-backward/ right-forward/ right-backward. Any ideas to create 4 extra functions for that?

Thanks for helping.

Update: Connection

int EN2 = 14;
int EN3 = 15;
int EN4 = 16;
int EN5 = 17;
int EA = 3;
int EB = 5;

Update: Attempted code and hardware connection

void left_top(void) {
  analogWrite(EA, 128); //speed 0 - 255
  analogWrite(EB, 255); //speed 0 - 255
  digitalWrite(EN2, LOW);
  digitalWrite(EN3, HIGH);
  digitalWrite(EN4, LOW);
  digitalWrite(EN5, HIGH);
}

void right_top(void) {
  analogWrite(EA, 255); //speed 0 - 255
  analogWrite(EB, 128); //speed 0 - 255
  digitalWrite(EN2, LOW);
  digitalWrite(EN3, HIGH);
  digitalWrite(EN4, LOW);
  digitalWrite(EN5, HIGH);
}

void left_down(void) {
  analogWrite(EA, 128); //speed 0 - 255
  analogWrite(EB, 255); //speed 0 - 255
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, LOW);
  digitalWrite(EN4, HIGH);
  digitalWrite(EN5, LOW);
}

void right_down(void) {
  analogWrite(EA, 255); //speed 0 - 255
  analogWrite(EB, 128); //speed 0 - 255
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, LOW);
  digitalWrite(EN4, HIGH);
  digitalWrite(EN5, LOW);
}

Left top / right top seem not to move at all, and right top / down is just similar to right / left.

And for hardware, I am using

Arduino  AR 293d

For the motor connection, it's like this:


texts:
I'm trying to reset an Arduino Pro Micro with a new code and it is not allowing me to. I'm using an empty sketch to upload to the pro micro but I get different error messages every time. I think the reason why it doesn't allow me to upload code is because it is programmed to start on boot. As soon as it's plugged in to a USB port the code runs, and causes this issue.

Some of the errors I get is

Arduino: 1.8.2 (Linux), Board: "Arduino/Genuino Micro"

Sketch uses 3602 bytes (12%) of program storage space. Maximum is 28672 bytes.
Global variables use 147 bytes (5%) of dynamic memory, leaving 2413 bytes for local variables. Maximum is 2560 bytes.
avrdude: ser_open(): can't open device "/dev/ttyACM0": Device or resource busy
Problem uploading to board.`

Does anyone know how I can fix this?


texts: Problem with nodemcu esp-01 can't connect to wifi

texts:
i've been working on a project that im using an esp8266 nodemcu-01 as described in the title, and i've been having some headache with this module, first because after searching i figured out that the commands LOW and HIGH are inversed as in LOW outputs 3.3v e HIGH outputs low tension, so i began to grow worried about the possibility that other programming resources may follow the same situation. But with that problem a part, i've been trying a few different codes including the one found in the sketchbook examples and still couldn't connect.

Also another weird problem, is that i was working working with the baudrate set on the arduino IDE settings on 115200, and so is the Serial.begin, that is also set to 115200, however i can only read properly the continuous dot that is contained in the while loop "........." when i set it to 74880, which another thing that i was trying to understand. I also forgot to mention that it keeps spamming dots but does not connect at all.

And to conclude, my problem resumes in not being able to connect to any wifi i've tried, i tried my friend's home and also 4g, both did not work, here's the code, which we tried first:

#include <ESP8266WiFi.h>

char* ssid = "Net Wi-fi";
char* password = "testingtest";
//
void setup() {
  WiFi.begin(ssid, password);
  Serial.begin(115200);
  while(WiFi.status()!=WL_CONNECTED)
  {
    Serial.print("Conecting");
    delay(500);
  }
  Serial.println("");
  Serial.print("IP:");
  Serial.print(WiFi.localIP());
}

void loop(){

This was the original try, using the arduino sketch example:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "Net6271";
const char* password = "megaman";

ESP8266WebServer server(80);

const int led = 13;

void handleRoot() {
  digitalWrite(led, 1);
  server.send(200, "text/plain", "hello from esp8266!");
  digitalWrite(led, 0);
}

void handleNotFound(){
  digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  digitalWrite(led, 0);
}

void setup(void){
  pinMode(led, OUTPUT);
  digitalWrite(led, 0);
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }

  server.on("/", handleRoot);

  server.on("/inline", [](){
    server.send(200, "text/plain", "this works as well");
  });

  server.onNotFound(handleNotFound);

  server.begin();
  Serial.println("HTTP server started");
}

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

Board setting: Generic ESP8266 Module.
Crystal Frequency: 40MHz.
Flash Frequency: 80Mhz.
Upload Speed: 115200.
Flash Mode: DIO.
Flash Size: 512k no SPIFFS.

pls help.


texts:
In the documentation of the nRF24L01 library I use (library), the CRC state (on/off) and length can be set or get. It seems to be used for auto ack, but when I switch auto ack off, what is the use of CRC? Can I somehow read the CRC value or use it somehow in a useful way?

The reason is, I get sometimes wrong values and would like the CRC for that, but otherwise I need to implement my own CRC byte(s) in the payload.

(also, when I put my finger against the PCB side on the side where the PCB antenna is placed, but not touching the antenna, I get many more messages).


texts:
i'm working on project now,
i need to save picture from camera VC0706 serial camera in specific folder on my PC, i found a tutorial (indonesian tutorial), thath give me code to use the camera, but they not tell me how to save the picture,
basically i need this image show on android phone, but i don't have money to buy a paid web server that can store image, so i want to use local webserver (PhpMyadmin using Xammpp) and call the image from htdoc folder, so i can show the image on android phoe

here is the code

 #include <Adafruit_VC0706.h>
#include <SoftwareSerial.h>

// Software serial & camera instance
SoftwareSerial cameraconnection = SoftwareSerial(2,3); // RX, TX
Adafruit_VC0706 cam = Adafruit_VC0706(&cameraconnection);

void setup() {

  Serial.begin(115200);
  Serial.println("Program Test Camera");

  // Try to locate the camera
  if (cam.begin()) {
    Serial.println("Camera Terbaca");
  } else {
    Serial.println("Camera Tidak Terbaca !!!");
    return;
  }

  // Set ukuran gambar
  cam.setImageSize(VC0706_640x480);   // Vga
  //cam.setImageSize(VC0706_320x240); // Qvga
  //cam.setImageSize(VC0706_160x120); // QQVGA
  // Tunggu 3 detik untuk capture
  Serial.println("Picture in 3 seconds ...");
  delay(3000);

  if (! cam.takePicture())
    Serial.println("Failed to capture!");
  else
    Serial.println("Capture Gambar OK ");
}

void loop() {
}


texts:
I have 2 nRF24L01+ modules that were working fine then...stopped. I'm wondering if I accidentally fried one of the modules.

When I run the RF24 library GettingStarted example, this is the output of the module I believe may be fried:

RF24/examples/GettingStarted/
ROLE: Pong back
*** PRESS 'T' to begin transmitting to the other node
STATUS        = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
RX_ADDR_P0-1  = 0x0000000000 0x0000000000
RX_ADDR_P2-5  = 0x00 0x00 0x00 0x00
TX_ADDR       = 0x0000000000
RX_PW_P0-6    = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA         = 0x00
EN_RXADDR     = 0x00
RF_CH         = 0x00
RF_SETUP      = 0x00
CONFIG        = 0x00
DYNPD/FEATURE = 0x00 0x00
Data Rate     = 1MBPS
Model         = nRF24L01
CRC Length    = Disabled
PA Power      = PA_MIN

I've changed out cables and connections all the way through. I also replaced this module with the other one directly and the other worked fine.

So, my question: Is this output showing definitively that I've killed the module and just need to buy a new one? Or is there some way to "flash" or reset the module?


texts: Concern myself with current draw from digital pins used as INPUT with internal pullups?

texts:
My project is using a genuine Arduino Mega 2560, probably 3-4 yrs old since purchased (I don't see any revision numbers on the PCB).  It's being used to read a lot of switches, buttons and drive some LED's and displays.

When using a digital pin as INPUT with the internal 10k pullup enabled, do I need to consider the draw with respect to the 200mA total through all pins?  Is it simply the 10k ohm resistor with 5V so 0.5mA?  Can I just ignore it? (there's only so many pins I suspect I can ignore it)

I've seen several posts/pages about driving LED's using transistor arrays powered by an external source and those spec sheets describe the transistor input currents so I can estimate the draws for those elements, but not sure if I need to concern myself with the Arduino pins used as INPUT.


texts:
I have a rock solid voltage on my analog input with ADC values jumping around by about 15% on the Serial monitor and LCD display
Never had anything like this before

Seeeduino V4.2
pinMode(A1, INPUT_PULLUP);
volt = analogRead(A1)

Am I the proud owner of a faulty board? ( wish I had a spare one to test )

regards
Wilfried


texts: Look for Master and Slave code with error for a Arduino Mege

texts:
I am building a a-10c Sim. So I need lots of input and outputs. Each Arduino has 54 digital i/o and 16 analog inputs in each. As I need more I just add another arduino mega 2560.

I want to thank in advance Im am very new at his, and would welcome any help.

Regards,

Gary
Im am a dyslexic so pls excuse the spelling or bed sentences


texts: Measuring 12 V via voltage divider: choosing the right resistors

texts:
I want to measure a 9 V battery via one of the analog input ports of my Arduino Nano. From all the schemes of this great answer, I choose the simplest one, the voltage divider. Assuming the maximum input voltage to be 12 V (just to be safe) and maximum divider's output voltage to be 5 V, I've solved it against R₂:R₁ proportion. It turns out that R₂:R₁ = 5:7.

simulate this circuit – Schematic created using CircuitLab

With the values above, the input of A0 pin will be exactly 5 V.

The problem is that it could be any values. 5 Ω and 7 Ω or 5 MΩ and 7 MΩ!

I understand, that there should be another equation to take into account that will give me the values of those two resistors. Another brilliant answer demonstrates, that the values depend on the current I want to flow through the branches:

  So the point is when determining the resistance of the resistors, we should take into account the input resistance of the load and the two voltage divider resistors should be as small as possible.

  On the other hand, let's compare the current going through the divider in the circuit with large resistors on the divider and the circuit with small resistors on the divider. As you can see, the large resistors have current of just 2.5 μA going through them and the small resistors have current of 25 mA. The point here is that the current is wasted by the voltage divider and if this was for example part of a battery operated device, it would have a negative impact on the battery life. So the resistors should be as large as possible in order to lower the wasted current.

9 V batteries are known to have a little of energy canned inside, with the most popular 6LR61 having only about 550 mA·h. I do not want to waste it on heating the resistors, so, probably, I need to use large resistors. But how large? Too large R₁ will let only a little current to flow to the A0 pin and I've read somewhere that small currents may lead to analogRead measurement errors (underestimations?) due to ADC's internal capacitor.

Trying to find the right answer, I've read on the Arduino's forum that:

  The ATmega328P datasheet has this info way in the back: Table 28-16 (page 328). The analog input resistance is claimed to be 100 Mohms.

  During an actual sample, the input resistance is temporarily a lot lower as the sampling capacitor is charged up so it is recommended that whatever you connect to the A/D have an output impedance of 10k or less for best accuracy.

And here, I am stuck. I understand that I am connecting a voltage divider to the A/D, but what is it's "output impedance"? It should depend on R₁ and R₂ somehow, and solving that equation (F(R₁, R₂) == 10 000) will give me the exact value…

P.S. I saw some cunning schemes in the Internet with capacitors, diodes and op-amps (everybody say it's super easy and safe to use them for this task), but, please:

I am just trying to understand the basics and making my first steps with electronics.
The device I'm making should be lightweight and compact (although I should be able to compose it without any PCB magic). Two resistors seems to be fine.
I'm going to read the voltage only once when the device is turned on, so I don't actually need super-fast op-amp's speed.
I'll try not to plug negative voltage, so I do not need a protection. Yet.


texts:
I have been looking through StackExchange, and searching on the web and cannot find an answer to my issue.

Setup:
Arduino Nano 168
HC-05 VERSION:3.0-20170601

I am trying to connect my Android phone to my Nano to control an output. I have found tons of varying examples, but they all basically boil down to MIT App Inventor to create app to connect via BT and send data to the Nano to control.

After many attempts with no results, I attempted the following:

#include <SoftwareSerial.h>

int light=8;
int Received=0;
int light_state =0;

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup(){

  Serial.begin(38400);
  pinMode(light,OUTPUT);
  BTSerial.begin(38400);

}

void loop(){
  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available()) {
    Serial.write(BTSerial.read());
 }

 if(BTSerial.available()>0) {
    Received = BTSerial.read();
 }

if (light_state == 0 && Received == '1') {
    digitalWrite(light,HIGH);
    light_state=1;
    Received=0;
  }
if (light_state ==1 && Received == '1') {
    digitalWrite(light,LOW);
    light_state=0;
    Received=0;
  }
}

So, when I run the MIT app on my phone to connect to the HC-05 the status LED on the HC-05 changes.  Before I connect, the status LED flashes fast.  After I connect, it flashes slow.

I have the serial monitor open on my laptop monitoring the Nano.  The HC-05 connects via pins 10 & 11.  When the phone connects to the HC-05, the data printed on the serial monitor is garbage.

⸮x⸮x⸮⸮x⸮x⸮x⸮⸮xxxxxx⸮x⸮⸮xx⸮⸮xxx⸮⸮

That is what I get.

The app is set to transmit a "1" via BT to the Nano.  When I press the button to send the 1, no data comes across.  But every time I pick the HC-05 and tell the app to connect to the unit, I get that same string of data above.

Thank you in advance for your help.


texts: How do i properly read an analog pin on attiny85?

texts:
Anyone ever run into a problem with your attiny not reading  your analog pins correctly? (-1023 or 1023 or 0 value) How did you resolve the issue?

Here's what my code looks like now :

4th revision of code as of 5/6/2015 8pm:

int NTC = A1; // thermistor
int switchPin = PB1; // push button
int LED = PB0;  // led

// button latch
byte ButtonState;
byte lastState = LOW;
byte count = 0;

 //brightness level of each different mode
int low = 50;
int med = 140;
int high = 255;
int dim = 0;

int ADCcount = 0;

void setup()
{

 pinMode(switchPin, OUTPUT);
 pinMode(LED, OUTPUT);

  }

 void loop()
 {

  ADCcount = analogRead(NTC);

delay(100);

  ButtonState = digitalRead(switchPin);

  if(ButtonState && ButtonState != lastState)  // button latch, no debounce      needed.
   {
      if(count < 4) // This will check to see if the count is within a range of  0 - 255
                 // anything over that, it will reset count back to 0. Of course
      count += 1;  // same as count = count + 5;
      else
      count == 0;
        }

    lastState = ButtonState;

   if (count == 0)
  {analogWrite(LED,0);}
    else if (count == 1) { if(ADCcount < 500) {analogWrite(LED,high);}
      else{ if(ADCcount > 525){analogWrite(LED,low);}
       }
          }
      else if (count == 2 ){analogWrite(LED,med);}
      else if (count == 3) {analogWrite(LED,low);}
      if(count >=4) {count = 0;}
      delay(50);
 }

simulate this circuit – Schematic created using CircuitLab


texts: How to Use Arduino Wifi Shield To Receive/Send Info

texts:
I am doing an engineering project where I am using an Arduino Uno to try to open a window with a motor when the device is activated. I want to activate it by using a phone to somehow send it a command to “turn on.” I have tried to use the ESP8266 but couldn’t get it working and now have an Arduino Wifi Shield but am very confused on how to use it to do this task. I am new to understanding Arduino so any help would be appreciated.

I found a tutorial on how to connect the wifi shield to internet on the arduino website but am not sure what I would do after this.

Thanks!


texts: How to control 2 micro magnetic actuators with esp12e

texts:
i want to control two micro magnetic actuators (just two coil where I want to flow current in +to- and-to+ each motor for wifi airplane) with esp12e
Do I need an h-bridge like l293d ?
Also I will be using mit app inventor any advice for it will nice:)))


texts: How to modify this code to simulate a binary encoder?

texts:
I have come across the following SPI slave code at this site:

#include <SPI.h>

char buf [100];
volatile byte pos;
volatile bool process_it;

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

  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // have to send on master in, *slave out*
  pinMode (MISO, OUTPUT);

  // get ready for an interrupt
  pos = 0;   // buffer empty
  process_it = false;

  // now turn on interrupts
  SPI.attachInterrupt();

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register

  // add to buffer if room
  if (pos < sizeof buf)
    {
    buf [pos++] = c;

    // example: newline means time to process buffer
    if (c == '\n')
      process_it = true;

    }  // end of room available
}  // end of interrupt routine SPI_STC_vect

// main loop - wait for flag set in interrupt routine
void loop (void)
{
  if (process_it)
    {
    buf [pos] = 0;
    Serial.println (buf);
    pos = 0;
    process_it = false;
    }  // end of flag set

}  // end of loop

How to modify the above code so that it responds to input clock signal just like in this SSI protocol? Uno or Nano can be used.

Basically I want to let an arduino  act as an absolute encoder so that it will transmit 13-bit binary data(it can be any random fixed binary data) as shown in the above SSI protocol. So the Arduino will output 13-bit binary data along with with start bit and tm taken into account as shown in the document above without parity.

The master's code I plan to use:

const int CLOCK_PIN = 2;
const int DATA_PIN = 3;
const int BIT_COUNT = 16;
void setup() {
    pinMode(DATA_PIN, INPUT);
    pinMode(CLOCK_PIN, OUTPUT);
    digitalWrite(CLOCK_PIN, HIGH);
    Serial.begin(115200);
  }
void loop() {
    float reading = readPosition();
    Serial.println(reading,2);
    delay(25);
  }

//read the current angular position
float readPosition() {
 unsigned long graysample = shiftIn(DATA_PIN, CLOCK_PIN, BIT_COUNT);
 delayMicroseconds(100); // Clock must be high for 20 microseconds before a new sample can be taken
unsigned long binarysample = grayToBinary32(graysample);
 return ((binarysample * 360UL) / 65536.0); // ouptut value from 0 to 360 with two point percision
}
//read in a byte of data from the digital input of the board.
unsigned long shiftIn(const int data_pin, const int clock_pin, const int bit_count) {
 unsigned long data = 0;
 for (int i=0; i<bit_count; i++) {
 data <<= 1; // shift all read data left one bit.

 //digitalWrite(clock_pin,LOW);
 PORTD &= ~(1 << 5); // clock pin goes low
 delayMicroseconds(1);
 //digitalWrite(clock_pin,HIGH);
 PORTD |= (1 << 5); // lock pin goes high
 delayMicroseconds(1);
 data |= digitalRead(data_pin); // cat the new read bit to the whole read data.
 }
 return data;
}
unsigned int grayToBinary32(unsigned int num)
{
 num = num ^ (num >> 16);
 num = num ^ (num >> 8);
 num = num ^ (num >> 4);
 num = num ^ (num >> 2);
 num = num ^ (num >> 1);
 return num;
}


texts: Powering ESP8266 from Leonardo's 3.3v pin

texts:
I'm new to Arduino, and I'm trying to connect my Leonardo via WiFi using a ESP8266 module. What I want to know is if I can power it directly from the onboard 3.3V pin like in the image:

Or do I need an external voltage regulator? I don't want to damage it.
Thanks!


texts: Can I program my Arduino using any programming language other than C++? If so, which programming languages? What software would I need for compiling and loading my code onto the Arduino?


texts:
I am trying to read the fuse values for the Arduino Uno, but keep getting the following results returned back to me:

enter code hereavrdude: Version 6.0.1, compiled on Dec 16 2013 at 17:26:24
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "/usr/local/CrossPack-AVR-20131216/etc/avrdude.conf"
     User configuration file is "/Users/hd334/.avrduderc"
     User configuration file does not exist or is not a regular file, skipping

     Using Port                    : /dev/cu.usbmodem1421
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200
     AVR Part                      : ATmega328P
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PC2
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
       lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : Arduino
     Description     : Arduino
     Hardware Version: 3
     Firmware Version: 4.4
     Vtarget         : 0.3 V
     Varef           : 0.3 V
     Oscillator      : 28.800 kHz
     SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0

avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0
avrdude: safemode: Fuses OK (H:00, E:00, L:00)

avrdude done.  Thank you.

I have tried using avrisp as the programmer too, but this reports an invalid device signature. If I override the device signature check with -F I get the same results as above.

I am using an Uno as the ISP to another uno and have connected the two together as detailed in
https://www.arduino.cc/en/Tutorial/ArduinoISP

I have boot loaded the Arduino Atmega328P boot loader and from the fuse settings given in the boards.txt file expect to see:
lfuse reads 0xff
hfuse reads 0xde
efuse reads 0x05

Another question is with the low fuse set to 0xff the CKDIV8 is programmed so won't the clock be set to 2MHz?

Please help


texts: Connection bluetooth master and slave with Android

texts:
I send a date from my android to arduino without problem, but also i want send date from arduino to android later of received the date from android.

I have time trying it, but i can not yet, help me.
My codec of arduino

char enter;
#include <SoftwareSerial.h>
SoftwareSerial conect(10,11);

void setup()
{
 pinMode(8,OUTPUT);
 conect.begin(9600);
 digitalWrite(8,LOW);
}

void loop()
{
 if(conect.available()>0)
  {
   enter=conect.read();
   if(entrada=='1')
   {
    digitalWrite(8,HIGH);
    conect.print("1");
   }
 }
}

And in the side from android this is my handler for drive the the date that arrive.

 Handler mhandler=new Handler(){
    @Override
    public void handleMessage(Message msg)
    {
        super.handleMessage(msg);
        switch (msg.what)
        {
            case CONECTADO:
                //ManejarDatos msjre = new ManejarDatos((BluetoothSocket)msg.obj);
                msjre = new ManejarDatos((BluetoothSocket)msg.obj);
                break;
            case MENSAJELEYENDO:
                byte[] readBuf = (byte[])msg.obj;
                String string = new String(readBuf,0,msg.arg1);
                Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG).show();
                break;
        }
    }
};

And on my class for read and write i have this

private class ManejarDatos extends Thread
{
    private final OutputStream salidadatos;
    private final BluetoothSocket sockk;
    private final InputStream entradadatos;
    public ManejarDatos(BluetoothSocket socke1)
    {
        sockk=socke1;
        OutputStream temporalsalida=null;
        InputStream temporalentrada=null;
        try
        {
            temporalentrada=socke1.getInputStream();
            temporalsalida=socke1.getOutputStream();
        }catch (IOException e){}
        salidadatos=temporalsalida;
        entradadatos=temporalentrada;
    }
    public void run()
    {
        byte[] espera;
        int esperaalmacen;
        while (true) {
            try {
                espera=new byte [1024];
                esperaalmacen=entradadatos.read(espera);
                mhandler.obtainMessage(MENSAJELEYENDO,esperaalmacen,-1,espera)
                        .sendToTarget();
            }catch (IOException e){break;}
        }
    }
    public void escribe(byte[] bytes)
    {
        try {
            salidadatos.write(bytes);
            //handler.obtainMessage(MENSAJE_SALIDA,-1,-1,bytes).sendToTarget();
        }catch (IOException e){
            //Log.e(TAG, "....Error al enviar dato" + e.getMessage() + "...");
        }
    }
    public void cancel()
    {
        try{
            sockk.close();
        }catch (IOException e){}
    }

}

When i push button, send a date to arduino, here my codec of button(i send 1 for bluetooth)

        Enviar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String salida="1";
            msjre.escribe(salida.getBytes());
        }
    });


texts: Cannot find COM port for Arduino after replacing Atmega328p

texts:
I had mistakenly burnt my ATmega328p that was there on the Arduino UNO R3 board. So I bought a new ATmega328p-pu with Arduino UNO bootloader installed and a sample blinking LED program pre-flashed.

However when I replaced it and plugged in to the PC using the provided Arduino programmer cable, I could not find the COM port in the device manager in Windows and neither in the Arduino IDE.

I should also mention that when I put the new Atmega328p-pu into the Arduino UNO board, the LED at 13 or L did start blinking. So I am inclined to think that both the bootloader and the sample program are there. But I cannot find the required COM port.

How do I fix this?


texts: Port Manipulation and serial communication

texts: i'm working on a laser timer using arduino and i saw that using direct port manipulation can have a really better time precision. My only concern is about serial communication, because i am using some pins for a software serial, and i don't know how to set them in the ports register. The pins are the 4 and 5, and the number 3 is the trigger output, unluckily this pinset cannot change. How should i set them in the DDRD? I'm using an Arduino Nano board


texts: Can I set an Arduino pin as input and output?

texts:
When I used to program PICs, there was a way to set the pins to input and output, at the same time. Can this be done on the Arduino?
I see the pinmode documentation, but nothing about being an IO port.


texts: How to fix why AT command gets no response from serial monitor for HC-05 Bluetooth module with Arduino Micro?

texts:
I am trying to send numeric data from master HC-05 to slave HC-05 Bluetooth module for the purpose of processing it. But I first need to pair the Bluetooth module. I have tried different tutorials and different circuit diagrams. I am currently using the using Arduino Micro and have my serial monitor set to 38400 baud rate and Both NL & CR activated. But I get no response from AT commands.
vcc->vcc
en->vcc
gnd->gnd
tx-> arduino rx
rx -> arduino tx using voltage divider where the main line goes from rx->1k-> arduino tx and the other line goes from rx-> 2k-> gnd.
I start by connecting the HC-05 according to the tutorial and  drive it into the AT mode by holding the button of HC-05 and plugging in the arduino putting it in AT mode indicated by long intervals between blinks(2-3 seconds). Then, I upload a blank sketch leaving rx and tx disconnected as per the tutorial. But AT mode doesn't respond to any of the AT commands when I try them on the serial monitor which has the baud rate set to 38400 as per HC-05 default and "Both NL & CR"  selected on the serial monitor.
I am using the Arduino Micro.
I am not using any code other than that the blank sketch at the moment. I just wanted to get the address of the slave module so that I can program the other module as the master and connect it to the slave. I tried the initial steps exactly as of the tutroial Link given below:
https://www.youtube.com/watch?v=hyME1osgr7s
I've tried other tutorials. Nothing seems to work. Some people just do rx-rx and tx-tx. But that doesn't work too.


texts: ESP8266 library / function for IR remote control

texts:
I am using IRremoteESP8266 for reverse engineering Hitachi AX-M76E mini stereos IR controller. I want to read the signal that the remote sends and send the same hexas to the stereos with IR led.

Please let me know if this is wrong site but I am trying to find out one thing on that IRremote library that is missing on it: code and protocol for Hitachi. There are even example code for Sony and other well known marks but Hitachi is missing.

Receiving IR is universal:

void loop() {
  if (irrecv.decode(&results)) {
    // print() & println() can't handle printing long longs. (uint64_t)
    // So we have to print the top and bottom halves separately.
    if (results.value >> 32)
      Serial.print((uint32_t) (results.value >> 32), HEX);
    Serial.println((uint32_t) (results.value & 0xFFFFFFFF), HEX);
    irrecv.resume();  // Receive the next value
  }
  delay(100);
}

With this loop I am able to fetch IR hex codes from remote control but with the next code I still cannot wake any action on stereos:

void loop() {
  Serial.println("NEC");
  irsend.sendNEC(0x00FFE01FUL, 32);// put the received hexa here
  delay(2000);
  Serial.println("Sony");
  irsend.sendSony(0xa90, 12, 2);
  delay(2000);
}

What you see every manufacturer uses their own protocol. I tested NEC because its protocol seemed to match what I received, still I did not succeed.

What may be the correct code, if I rewrite the sendNEC function so that I get the Hitachi one?


texts: Parallel connection to Wiegand 26bit RFID readers

texts:
I have situation where I need to read RFID cards. There is already installed Roger security system, Roger gate control board and two rfid readers in parallel. By default board and RFID readers communicate in RACS(some sort of coded protocol) but at the moment system is configured to communicate in Wiegand26. Earlier I used chinese wiegand26 reader with Arduino with no problem.

With Arduino I need to read card read by RFID readers.
Then I process data and make HTTP POST request.
Arduino is supplied from Roger board ~13.5V DC I do not get anything in arduino, even if I connect RFID readers directly to arduino.

CLK is D0 to Arduino Nano pin 2
DTA is D1 to Arduino Nano pin 3

This question is not related only to Arduino.

I want to ask is it possible to do? To read data maybe I need some additional electronics?

What i also noticed that when Arduino is connected in parallel the Roger board not always reads the card from RFID readers.

Roger PR402-BRD
And two readers PRT62LT

This is copy of Electronics.stackexchange


texts:
I want to store a few (8 as of now) IR codes into my Board's EEPROM.
It would be great if someone could suggest a few tips to maximize the lifetime.

The IR codes in my sketch are saved in array of unsigned longs.

I know that the count of times that I will be writing to EEPROM will << 100,000 times, but still would like to optimize my sketch. + would help in future projects


texts: I received a Adafruit Feather 32u4 FONA as a gift and have read the great, comprehensive document Adafruit put have put together surrounding pinouts, examples etc for the board. I am having issue understanding the section on the KEY pin, I understand that it is used to put the cellular module to sleep, but in order to do this it is mentioned to “cut the trace and wire it to a micro controller pin”. Does this mean that in order to utilize the on/off functionality of the SIM module I have to slightly butcher my new shiny board instead of using the pin directly?


texts: SerializeJson not working when using softserial

texts:
IDE:1.8.8
Board:Arduino UNO
When I use the code below, I get result of print like this.

{ "result": [ { "ID": "01", "Value": [ "2", "1", "13" ] } ] }

But when I use SoftwareSerial and in the setup to being that the serializeJson result like this:

{}

I don't know what happens in the softserial with using json library, can someone tell me why?

#include <SoftwareSerial.h>
#include <ArduinoJson.h>
int dir[3];
char  json[] ="{\"ID\":\"01\",\"Value\":[\"%d\",\"%d\",\"%d\"]}";
//SoftwareSerial Left(8,9);//左
/SoftwareSerial Right(6,7); //右
//SoftwareSerial Up(10,11);//上
//SoftwareSerial Down(14,15);//下
//SoftwareSerial Global(8,9);  //建立軟體串列埠腳位 (RX, TX)左
void setup() {

  Serial.begin(9600);        //設定硬體串列埠速率
 // Up.begin(9600);
 // Right.begin(9600);
  //Global.begin(9600);   //設定軟體串列埠速率
  }

void loop() {

 dir[0]=2;
 dir[1]=1;
 dir[2]=13;
  if(Serial.read()=='j')
{
 StaticJsonDocument<256> docc;
  char b[35];
  sprintf(b, json, dir[0], dir[1],dir[2]);
  deserializeJson(docc, b);
  JsonObject object = docc.as<JsonObject>();

  DynamicJsonDocument doc(1024);
 JsonArray result = doc.createNestedArray("result");
  result.add(object);
  result.add(object);
  serializeJsonPretty(doc,Serial);
   }
  }

These are error code

#include <SoftwareSerial.h>
#include <ArduinoJson.h>
int dir[3];
char  json[] ="{\"ID\":\"01\",\"Value\":[\"%d\",\"%d\",\"%d\"]}";
//SoftwareSerial Left(8,9);//左
SoftwareSerial Right(6,7); //右
SoftwareSerial Up(10,11);//上
//SoftwareSerial Down(14,15);//下
SoftwareSerial Global(8,9);  //建立軟體串列埠腳位 (RX, TX)左
void setup() {

  Serial.begin(9600);        //設定硬體串列埠速率
  Up.begin(9600);
  Right.begin(9600);
  Global.begin(9600);   //設定軟體串列埠速率
  }
void loop() {
     Global.listen();
      while (!Serial.available()) {}  //等到PC傳送字元才到下一步
     Global.write(2);  //傳送給左邊的板子子id
      while (!Global.available()) {}  //等到左方板傳送字元才到下一步
        dir[0]=Global.read();
        Serial.println( dir[0]);  //左方板向PC傳送字串

       Up.listen();
      while (Serial.read()!='Y') {}  //等到PC傳送字元才到下一步
      Up.write(3);  //傳送給左邊的板子子id
      while (!Up.available()) {}  //等到左方板傳送字元才到下一步
      dir[1]=Up.read();
        Serial.println(dir[1]);  //左方板向PC傳送字串
       // }

     Right.listen();
     while (Serial.read()!='Y') {}  //等到PC傳送字元才到下一步
      Right.write(4);  //傳送給左邊的板子子id
      while (!Right.available()) {}  //等到左方板傳送字元才到下一步
       dir[2]=Right.read();
        Serial.println(dir[2]);  //左方板向PC傳送字串
 if(Serial.read()=='j')
{
 StaticJsonDocument<256> docc;
  char b[35];
  sprintf(b, json, dir[0], dir[1],dir[2]);
  deserializeJson(docc, b);
  JsonObject object = docc.as<JsonObject>();

  DynamicJsonDocument doc(1024);
 JsonArray result = doc.createNestedArray("result");
  result.add(object);
  result.add(object);
  serializeJsonPretty(doc,Serial);
   }
}


texts: Neo 6M + ESP32 unable to take a fix on battery but works fine with laptop USB

texts:
I am using Neo 6M GPS module with ESP32 and 2 X 3.5V(7 v in series) 18650 lithium ion battery stepped down to 5V using LM2596 buck converter.
Problem which I am facing is when I power ESP32 using 5V output of LM2596 by connecting Vin pin and powering Neo6M using 5V output of buck converter or 3.3 V of ESP32 then my Neo 6M is unable to fix on satellite, however when removing battery and LM2596 and powering ESP32 using laptop usb cable and Neo 6M using 3V pin of ESP32 then its able to take a fix in 1 minute.
Any idea what mistake I could be doing.
Note - When using battery ESP32 is working as normal and able to connect to wifi and submit Tiny GPS++ output everysecond.
Please let me know in case more information required.


texts: Using Analog Comparator on Uno to Read Differential Voltage Signaling

texts:
I am trying to use the Arduino Uno to read an AVCLan bus on a Toyota vehicle.  Logic 0 is when +/- drive are 120mV or more apart, and logic 1 is 20mV or less.  See Toyota AVC-Lan description.

I currently set the TCNT1 timer to /1 prescaler for resolution, and waiting in a loop until the ACO bit sets in ACSR.  Using this, I measure the amount of time the signal was logic 0, and calculate each bit based on the how long the timer ran, and then resetting it.

While this works fine for most messages, I do receive a "glitch" every couple messages, with on-times around 2uS - 4uS, which shouldn't happen on this bus.  I'm guessing the analog comparator is tripping up if the drive is around 10mV - 20mV, when it shouldn't set.

Is there any way to set up a threshold, so that it will only fire the comparator at say 100mV or above?


texts:
I want to move the mouse pointer with an Arduino and ultrasonic sensor but when I compiled it says

  Mouse.h not found

and I don't know what I can do.

Here is my code;

 #include <Mouse.h>

int echoPinCursor=2;
int trigPinCursor=3;

int echoPinBtn=4;
int trigPinBtn=5;
int echoPinScroll=6;
int trigPinScroll=7;
int x;
int y;
long duracionCursor, distanciaCursor;
void setup() {
 Serial.begin(9600);
 pinMode(trigPinCursor, OUTPUT);
 pinMode(echoPinCursor, INPUT);
 pinMode(trigPinBtn, OUTPUT);
 pinMode(echoPinBtn, INPUT);
 pinMode(trigPinScroll, OUTPUT);
 pinMode(echoPinScroll, INPUT);

}

void loop() {

    //mover el cursor
  int direccionx=moverx();
  int direcciony=movery();

  Mouse.move(direccionx, direcciony,0);
  delay(2);

}

int moverx(){
      distanciaCursor=obtener_distanciaCursor();
  if (distanciaCursor >= 1  || distanciaCursor <= 11){
       x--;
     }
   if (distanciaCursor >= 12 || distanciaCursor <= 24){
       x++;
      }
     return x;
}

int movery(){
      distanciaCursor=obtener_distanciaCursor();
     if (distanciaCursor >= 25 || distanciaCursor <= 37){
       y--;
       }
   if (distanciaCursor >= 38 || distanciaCursor <= 50){
       y++;
      }
  return y;
}

long obtener_distanciaCursor(void)
{
  digitalWrite(trigPinCursor, LOW);
 delayMicroseconds(2);

 digitalWrite(trigPinCursor, HIGH);
 delayMicroseconds(10);

 digitalWrite(trigPinCursor, LOW);
 duracionCursor = pulseIn(echoPinCursor, HIGH);

 distanciaCursor = duracionCursor/58.2;
return(distanciaCursor);

}


texts:
I'm still learning the basics so please bare with me if something seems unclear ;-)

I want to hook up an Attiny85 to a WiFi module (esp8266) and 2 sensors. The VCC will be provided by a battery pack and a step-up/step-down converter to ensure steady voltage without too much efficiency loss. Right now the modules are all hooked up to the VCC rail, together with the Attiny85 in one circuit.

I would like to take a sample, and then make as much of the circuit power down until the next reading with a 2 minute interval or so.

While looking for power saving modes for the esp8266 and struggling a bit with it, it got me thinking. What if I let Attiny85 handle the WiFi and sensors circuit via an OUTPUT pin and just turn that high or low. I read somewhere that an OUTPUT pin would not be able to supply as much current as if it was directly connected. That would probably be the case for me here since the WiFi module draws significant current.

Maybe using a transistor to "flip the switch" be a good solution instead if that is the case?

So my question is, is my way of thinking here even viable? How do I know what kind of max current can go through an OUTPUT pin?


texts:
Are there board-independent functions to check pin capabilities at compile time? I.e.

Can the pin be used as output, as in digitalWrite()?
Does the pin support PWM, as in analogWrite()?
Does the pin support ADC, as in analogRead()?
Does the pin support interrupts, as in attachInterrupt()?

I'm looking for functions/macros like e.g. isDigitalOutput(pin) which would return false for input-only pins such as A6 and A7 on a 328P, but true on a Mega where those pins are input/output.


texts: What are the negative PINs for on the IndustrialShield M-Duino 58 Analog

texts:
I am working as an internship on an Arduino based PLC. It is the M-Duino 58 Analog from IndustrialShields. I try to figure out how it works; Reverse Engineering. But i dont know why it has negative Digital Inputs like normal Digital Input I1.0 also has a connection -I1.0.
It is probably a simple question but i cant figure it out. Hope you guys can help me.

I guess i figured it out. Seems to be the GND connections. Should read the Manual better next time.


texts: HUGE deviation in Sharp IR sensor values if other pins are defined in void setup()

texts:
I wrote this code for a project -

int sensorpin = A5;
int val = 0;
double avgval = 0;
int E1 = 11;
int brake = 12;
char data = ' ';

void setup()
{
  Serial.begin(115200);
  pinMode(E1, OUTPUT);
  pinMode(brake, OUTPUT);
  pinMode(sensorpin, INPUT);
}

void loop()
{

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

  val = analogRead(sensorpin);
  avgval = average(val);
  double volt = (avgval*5)/1023;
  Serial.println (avgval);
  Serial.println(volt);
  delay(1000);

  if (data == 'G'){
    analogWrite(E1, 255);
    digitalWrite(brake, LOW);
  }

  if( volt > 1.5 && volt < 1.75 ){
    digitalWrite(brake, HIGH);
  }
}

double average(double adc){
  int n = 1;
  double avg = 0.00, sum = 0.00;
  while(n<=23){
    sum = sum + adc;
    avg = sum/25;
    n++;
  }
  return avg;
}

The code works fine, except for the fact that the Sharp IR sensor (GP2Y0A710K0F) outputs values which are wrong (by a HUGE distance), ONLY if in the void setup() function, the commands -

pinMode(E1, OUTPUT);
pinMode(brake, OUTPUT);

are left uncommented. If I comment the above two statements, the sketch works fine.

What on earth is wrong here? I can't make out anything.


texts: My arduino is connected to ultrasonic sensor and I am trying to read the value from it. When I tried running "tail -f > /dev/ttyACM0" my arduino is sending some weird characters that I am not able to decode


texts: How to switch between multiple BMP180 sensors?

texts: I have six BMP180 sensors for measuring temperature and pressure. The problem is that I can get the value from one sensor but I need values from all six sensors using a single Arduino Mega board. How can I do that? I have already tried powering each sensor with digitalWrite but that didn't work. If you have a solution, can you also provide the code for that?


texts: Where am I supposed to get an I2C BUFFER_LENGTH defined?

texts:
I am using a BLE nano - as soon as I try to include I2Cdev.h and compile, I get this error:

Arduino\libraries\I2Cdev\I2Cdev.cpp:276:62: error: 'BUFFER_LENGTH' was not declared in this scope

How should I fix this? I imagine I can hard-code it in and guess around as to the value (32 seems common), but I think I am missing something else as far as it using the right libraries for the hardware, so how can I check/fix that if it is indeed the case?


texts:
The project I'm planning is to use a NodeMCU at each electrical board in house to control lights and fans via relays. Each MCU will communicate via MQTT over WiFi to a Raspberry Pi 4 from where I can control all lights and fans in the house. My doubt is:
Can the 3.3V NodeMCU drive a 5V relay like this 1 Channel 5V Relay Module with Optocoupler since I can't find any 3.3 V relays in India. Or must I use a logic level shifter? Or just use an ESP32 board (double price).


texts: BT shield to receive/intercept BT mouse data

texts:
I've owned this HC-05 shield for a long time, but actually never used it, until the need arose.

There is a rather delailed wiki on how to use it, either as BT Master or Slave.
I also have a BT mouse. With all these buttons and the wheel, a mouse can make a wonderful remote controller.
However, the shield doesn't support the HID protocol, that the mouse speaks.
Is there any way to trigger the mouse to "speak" to the shield? I just need to read the controls buttons/wheel controls that the mouse sends (and it seemingly won't send them unless it's paired with a device).


texts: Reproducing a Fiber Optic Shape Sensor with Arduino?

texts:
I want to be able to track the curvature of a human arm as it straightens out and retracts (ex: like live tracking a bicep curl). I don't want to use resistive flex sensors.

I've been trying to find suppliers for this technology demoed here: https://www.youtube.com/watch?v=iAeXp-TpFLU&t=38s

But I cant seem to find anyone who sells directly to consumers. I was thinking about creating a hobbyist level version my own using fiber optic wire, a led, and a light wavelength sensor, using a more powerful Arduino such as the Intel Edison. I have a basic understanding of how this technology works, but I want to learn by attempting to create it.

Is this practical or possible with an Arduino?

if so:

Are these the correct materials I would need?

if not:

Why not?
What kind of equipment would I need to achieve this?
Is there anywhere to buy this sensor directly?
Are they any alternatives for 3D shape/position sensing besides 3D magnetic sensing?


texts: Arduino + CO2 + humidity + noise + temperature sensors on one board

texts:
I'm looking for an Arduino board that include this sensors out of the box:

CO2
Humidity
Noise
Temperature

I've found here Using the Waspmote Sensor Board something that could be enough, but I'm searching for more options.

I did a lot of searches on the Internet without good results.

Any suggestions?


texts: is PIN To PIN matching mcu against Atmega328P-AU available?

texts: I want to upgrade my product which is based on Atmega328p-AU, having the problem of programming memory. I don't want to change the PCB of the product. Is PIN To PIN matching MCU against Atmega328P-AU available?


texts: Compiling Error - exit status 1 for DHT11 using Arduino UNO (code/process/connections same as website given bellow)

texts:
https://create.arduino.cc/projecthub/MisterBotBreak/how-to-use-temperature-and-humidity-dht-sensors-9e5975
Copied Error Message:
Arduino: 1.8.13 (Windows 10), Board: "Arduino Uno"

In file included from C:\Users\soumy\OneDrive\Documents\Arduino\libraries\DHT-sensor-library-master\DHT_U.cpp:15:0:

C:\Users\soumy\OneDrive\Documents\Arduino\libraries\DHT-sensor-library-master\DHT_U.h:36:10: fatal error: Adafruit_Sensor.h: No such file or directory

 #include <Adafruit_Sensor.h>

          ^~~~~~~~~~~~~~~~~~~

compilation terminated.

exit status 1

Error compiling for board Arduino Uno.

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

The code:
#define DHTPIN 2
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");

  dht.begin();
}

void loop() {

  delay(2000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);

  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  float hif = dht.computeHeatIndex(f, h);
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F");
}


texts: 9v adapter burned out Leonardo style board

texts:
My first experience with Arduino ended in a tragedy. I bought a Leonardo from ebay and upon arrival, attached it to my laptop. Programmed a simple blink demo with the onboard LED. It started working. Then detached it from USB and plugged in a 9v adapter. The board started smoking and it doesn't work anymore. I measured the voltage of the adapter and it reads 9.7v. So, what is the reason of this tragedy?

Edit:

I think that the smoke was from a component close to the processor. Right now, when I attach a 9v battery to the board, both the ON LED and the L LED remains on. The processor also warm.


texts: Is it possible to use extra AVR Flash memory as non-volatile EEPROM-like Flash memory storage?

texts:
In STM32 microcontrollers it is possible to use a technique that ST calls IAP, or In-Application Programming, in order to write to the Flash memory from your running application. They even have a nice Application Note (ex: AN2594) to describe a really ingenious way to use two Flash memory pages to emulate EEPROM while using "wear-leveling" to reduce Flash memory wear during erase cycles.

I have wondered for years: can AVR do this? Ex: the ATmega328 mcu in the Arduino Uno, Nano, etc--can you write code to store data from your application into Flash memory, thereby increasing non-volatile storage space for data acquisition for instance?

If so, can you please point me to some resources or examples, including example code, reference manuals or datasheets, etc, that might help me implement this? I've done some looking in the datasheet and haven't found anything so far but maybe I'm just not looking hard enough or know well enough what I'm looking for.


texts:
I'm using a port of the STL found here and trying to debug with a simple try{...}catch{...} loop. When compiling with the Arduino IDE, I get the error message

  exception handling disabled, use -fexceptions to enable.

I'm not quite sure what this means. Can the Arduino simply not support exceptions? Or is -fexceptions a compiler flag I can enable?


texts: TSX0108 logic level converter not working

texts:
Am trying to setup logic level converter with arduino for eps8266 WiFi module. Am using this logic level converter but it’s not working not sure what am doing am not getting any output.

My circuit

Red wire : 3.3v power source
Orange wire : 5v power source
Blue wire : ground.
Yellow wire : arduino TX1 on B2
White wire : output on A2

Multi meter it red wire : 3.3 v showing on display

Multi meter it orange wire : 4.68 v showing on display

Multi meter it yellow wire : 4.36 v showing on display

**Multi meter it white wire : no voltage showing on display ??? **

Update : have set OE pin to enable and swapped red and orange. Still no output for yellow wire


texts: Automate capturing photograph on ESP32-CAM

texts: I want to capture photographs from the ESP32 camera, but not doing it manually. Specifically, when a signal is sent from a sensor, I want ESP32 to understand that, and start taking photographs automatically for some seconds. The main problem, is the automation. I have searched on the web a lot, but can't find any answers. I am not expecting answers with code -since this is difficult- rather than some sites that provide solution to my problem. Thank you.


texts: Why does controlling power with a transistor interfere with MHZ19B's serial communication?

texts:
I've been trying to turn off an MHZ19B (datasheet and teardown photos: revspace.nl/MH-Z19B). I've used an Arduino, NPN, PNP transistors and mosfets as well as the diagram below for connecting the sensor to an ESP32. In all cases, PWM communication works great! I can power off the sensor, turn it back on, and values derived from PWM communication are as expected. However when I connect the Rx and Tx lines (to software serial Tx and Rx pins respectively on Uno pins A0 A1 or ESP32 pins 32 33) they spit out gibberish and the PWM signal also suffers hiccups.
Otherwise, without any kind of logic power control, the MHZ19B works great and can communicate with anything via UART, even my PC usb port via FTDI.
I added resistors to the Rx and Tx lines so the voltage on them doesn't exceed Vcc. I tried 1n4007 diodes (they're the only ones I have; no Schottky diodes either). I tried an NPN equivalent optocoupler. I also tried powering the sensor from my breadboard. I don't own an oscilloscope :(
My High School teacher said to just use PWM, but as I searched for a solution to this error, I noticed hundreds of others have this exact same problem with all sorts of different sensors and loads with ICs; no one has come up with a general solution.
I've been obsessing with this for weeks and if anyone can help or can recommend a book about sensor schematics I would really appreciate it. Thanks!


texts: ESP8266 Arduino 2.2inch ILI9341 TFT library

texts:
I recently got one TFT LCD from aliexpress which supports SPI and uses ILI9341.
This is the one.TFT LCD
I have the ESP8266 EspressoLite 1 board, and I am using ESP8266 Arduino.
(https://github.com/esp8266/Arduino)
I made the following connection :
SCK #14, MOSI #13, MISO #12 and CS #4, DC #5,RESET #0
and used the example graphicTest (which is available in the Adafruit_ILI9341-master folder) . I was able to make the display work for a few seconds.
In the graphic test, once the line test starts my ESP8266 gets restarted. This was getting repeated .
In my existing project, I used the following code to just show some messages :
Adafruit_ILI9341 tft = Adafruit_ILI9341(4, 5, 13, 14, 0, 12);
  tft.begin()
  tft.fillScreen(ILI9341_BLACK);
  tft.setCursor(0, 0);
  tft.setTextColor(ILI9341_GREEN);  tft.setTextSize(4);
  tft.println(message);

The message is shown once a response is sent back from ESP. This works for a couple of times and then it again gets stuck and reboots.
I am not sure whether I am using the optimised library for ESP8266 for this LCD or whether there is any as such.
I read in forums and could see that there were some adafruit libraries in the ESP8266 Arduino but now that it is not available and only some TFT_Touch_Shield_V2 are present.
Has anyone faced the same issue or can tell me a better way to make this display work with ESP8266 Arduino.
Thanks in advance. !!!


texts: How to measure electrical conductivity using Arduino?

texts: I want to measure TSS(Total soluble salt) in soil. I have found in some literature that, through measuring of electrical conductivity, it is much easier to measure TSS. So, I thought, If I can measure electrical conductivity, it might be possible to find out TSS. (Logic behind the TSS is that, pure water is poor conductor of electric, increasing of soluble salt in water proportionately lift up the conductivity). So are there any sensor that readily measure conductivity. A point I also want to mention, can a voltmeter be useful for that.


texts: making power harmonics analyser which will measure the amplitudes of the fundamental and its multiples (like 50hz, 100hz, 150hz,200 hz,...) there are)

texts:
i have been  intendng to make a power frequency harmonics analyser which will measure the amplitudes of the fundamental and its multiples (like 50hz, 100hz, 150hz,200 hz,...) there are examples for making spectrum analyser with fft library's here is the example for the kosome made fft library

   #include <arduinoFFT.h>

   #define SAMPLES 128             //Must be a power of 2
   #define SAMPLING_FREQUENCY 1000 //Hz, must be less than 10000 due to ADC

   arduinoFFT FFT = arduinoFFT();

   unsigned int sampling_period_us;
   unsigned long microseconds;

   double vReal[SAMPLES];
   double vImag[SAMPLES];

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

        sampling_period_us = round(1000000*(1.0/SAMPLING_FREQUENCY));
   }

   void loop() {

        /*SAMPLING*/
        for(int i=0; i<SAMPLES; i++)
        {
            microseconds = micros();    //Overflows after around 70 minutes!

            vReal[i] = analogRead(0);
            vImag[i] = 0;

            while(micros() < (microseconds + sampling_period_us)){
            }
        }

        /*FFT*/
        FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
        FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD);
        FFT.ComplexToMagnitude(vReal, vImag, SAMPLES);
        double peak = FFT.MajorPeak(vReal, SAMPLES, SAMPLING_FREQUENCY);

        /*PRINT RESULTS*/
        //Serial.println(peak);     //Print out what frequency is the most dominant.

        for(int i=0; i<(SAMPLES/2); i++)
        {
            /*View all these three lines in serial terminal to see which frequencies has which amplitudes*/

            //Serial.print((i * 1.0 * SAMPLING_FREQUENCY) / SAMPLES, 1);
            //Serial.print(" ");
            Serial.println(vReal[i], 1);    //View only this line in serial plotter to visualize the bins
        }

        //delay(1000);  //Repeat the process every second OR:
        while(1);       //Run code once
   }

how can i seperate the amplitudes for particular frequencies like amplitude of 50hz = ?, 150hz = ? and store them in other variables


texts: How does one wire OV7670 camera with Arduino Due?

texts:
The parts that I want to interface together are:

Arduino Due
OV7670 Camera Module
3.5" TFT Touchscreen LCD (uses MCUFRIEND_kbv library)

My goal is to get the video feed from the camera to the LCD screen. Any help will be appreciated.


texts: Need help modelling and coding a feedback scenario

texts:
Above illustration is the basic setup for the question. The scenario will be the following:

  A potentiometer(providing 0 to 5V) is an analog input to A0. This
  potentiometer voltage is converted to PWM(pin9) which controls a fan M1. Which
  means the human controls directly the M1 fan speed.

  This directly speed-controlled M1 fan creates air pressure on a sensor
  Sen1.

  On the other hand I want M2 fan to reach to a speed(via pin10 PWM) such that Sen2
  should output the same voltage as Sen1. Which means eventually voltage
  at A1 analog input should be equal to A2. So one can achieve same air pressures at Sen1 and Sen2.

I'm not experienced in PID or other type of controls. I would be glad if someone can help me to relate parameters and code this scenario.


texts: Turn off power to a moisture sensor except when reading values

texts:
I have an Arduino Uno and a moisture sensor (looks like a YL-69 clone) submerged in water. I need to read the sensor's (analog) value every 3 min or so. The problem is: the sensor is always powered by the Arduino (GND and VCC), i.e. the current passes through it at all times. Because of this, one of the sensor's electrodes (presumably containing copper) grows a cyan residue. I'd like to NOT supply any power to the sensor except for the brief moment when I need to read the value. How can I do this?

EDIT: I've just noticed a related question (link below). The user decided to intermittently power the sensor via a digital pin, rather than VCC. Is this reasonable?

Does a moisture sensor need warm-up time?


texts: Program arduino via USB while using a Bluetooth module (HC-06)

texts:
I have my Arduino Nano connected to the HC-06 module (with the RX/TX pins).

My issue is that when I try to upload new code to my Arduino (via the Arduino IDE, through the USB connection) the Arduino IDE doesn't succeed.

I get this error:

  avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

I believe that it is just trying to upload the code to the HC-06 (instead of the Arduino). Is there a way to overcome this issue?.

Thanks.

Note: I found this entry https://stackoverflow.com/questions/27175937/arduino-program-upload-while-btooth-module-connected-avrdude-stk500-getsync indicating that it wasn't possible (that I need to unplug the module). I am trying to confirm it.


texts:
I have an L293 motor driver chip, in which the two input pins are used in order to turn the motor forward or reverse, or stop it. So I wοnder if I could use only one input pin, ...

For running mode: Since Input1 should be the opposite of Input2, why not sending a signal from Input1 to Input2 via a hex inverter?

For stop mode: why not just sending analogWtite(Enable, 0) to Enable pin?

That way I could save an extra Output pin from Arduino. Do I lack some important detail?

My question goes the same for all the L29x family.


texts:
I would like to connect my custom-made Arduino with an Ethernet shield but I'm not so sure I can.
The problem
My board is using the design from the Arduino Mini which lacks the ATmega16U2 which does the USB-to-serial conversion and adds the ICSP pins. I think you get the point... I have only the ATmega328P on the board. Nothing else.
Is it even possible to work my way around it without adding the ATmega16U2? I can't find the chip anywhere on Ebay.


texts: Arduino Nano off 9V : is there any change to output?

texts:
I'm building a test circuit on an Arduino Nano that consists of a simple 220 Ohm resistor and an LED on pin D2 which is routed back to GND (ground).

It's as simple as this:

It's running a very simple program to blink the LED on and off.  It all works while connected to the USB port.  I know the USB port provides 5V.

Now I want to run it my Nano and circuit from a 9V battery.  The datasheet says that you can run the Nano on 6V -12V by connecting it to pin 30 (VIN).  Of course, I know I'll have to add a line from GND back to the (common) battery ground also.

When I do that, the voltage on the OUTPUT pin (D2) will never be higher than 5V though, right?
I should not expect any change in output voltage even though I'm changing voltage that is powering the Nano, correct?


texts: Setting a fixed receiver frequency RDA5807m

texts:
I am using the receiver RDA5807m, but I do NOT need to switch the frequency and other parameters during operation.

I noticed that the module continues to work when the programming pins are disconnected during its operation, that is, it remembers the settings until the supply voltage is removed.
Therefore, I want to set the frequency and volume at the beginning of work, so as not to occupy the resources of the microcontroller, but I just understand the registers. Tell me how to write code, the simplest of all possible configurations for this purpose.
Now I am using the following sketch, it works, but it takes a lot of resources, and I don't need it. Help simplify it and free it if possible "void loop()"
#include <Wire.h>

#define RDA5807M_RANDOM_ACCESS_ADDRESS 0x11
// registers
#define RDA5807M_REG_CONFIG 0x02
#define RDA5807M_REG_TUNING 0x03
#define RDA5807M_REG_VOLUME 0x05
#define RDA5807M_REG_RSSI   0x0B
// flags
#define RDA5807M_FLG_DHIZ 0x8000
#define RDA5807M_FLG_DMUTE 0x4000
#define RDA5807M_FLG_BASS 0x1000
#define RDA5807M_FLG_ENABLE word(0x0001)
#define RDA5807M_FLG_TUNE word(0x0010)
//masks
#define RDA5807M_CHAN_MASK 0xFFC0
#define RDA5807M_CHAN_SHIFT 6
#define RDA5807M_VOLUME_MASK word(0x000F)
#define RDA5807M_VOLUME_SHIFT 0
#define RDA5807M_RSSI_MASK 0xFE00
#define RDA5807M_RSSI_SHIFT 9

uint8_t volume = 15; // 0..15
uint16_t freq = 1073; // 107.3FM
uint16_t reg02h, reg03h, reg05h, reg0Bh;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  // Register 02h - enable, settings
  reg02h = RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
  setRegister(RDA5807M_REG_CONFIG, reg02h);

  // And then we decided to further strengthen the bass:
  reg02h |= RDA5807M_FLG_BASS;
  setRegister(RDA5807M_REG_CONFIG, reg02h);

  // Register 03h - radio station selection
  // After reset in register 03h, the default value is 0
  // Thus BAND = 00 (87..108MHz), STEP = 00 (100kHz). Let's leave them as they are
  reg03h = (freq - 870) << RDA5807M_CHAN_SHIFT; // chan = (freq - band) / space
  setRegister(RDA5807M_REG_TUNING, reg03h | RDA5807M_FLG_TUNE);

  // Register 05h. Set the volume, do not change the rest of the beats
  reg05h = getRegister(RDA5807M_REG_VOLUME); // read the current value
  reg05h &= ~RDA5807M_VOLUME_MASK; // Resetting the VOLUME bits
  reg05h |= volume << RDA5807M_VOLUME_SHIFT; // Set a new volume
  setRegister(RDA5807M_REG_VOLUME, reg05h);
}

void loop() {
  // Register 0Bh - status
  reg0Bh = getRegister(RDA5807M_REG_RSSI);
  uint8_t RSSI = (reg0Bh & RDA5807M_RSSI_MASK) >> RDA5807M_RSSI_SHIFT;
  Serial.print("RSSI = ");
  Serial.print(RSSI);
  Serial.println(" (0-min, 127-max)");
  delay(500);
}

void setRegister(uint8_t reg, const uint16_t value) {
  Wire.beginTransmission(0x11);
  Wire.write(reg);
  Wire.write(highByte(value));
  Wire.write(lowByte(value));
  Wire.endTransmission(true);
}

uint16_t getRegister(uint8_t reg) {
  uint16_t result;
  Wire.beginTransmission(RDA5807M_RANDOM_ACCESS_ADDRESS);
  Wire.write(reg);
  Wire.endTransmission(false);
  Wire.requestFrom(0x11, 2, true);
  result = (uint16_t)Wire.read() << 8;
  result |= Wire.read();
  return result;
}

I found a really short sketch that allows you to set the frequency. It remains to set the volume in the same way.
#include <Wire.h>
float f = 104.7;

void setFrequency(float frequency)
{
  unsigned int frequencyB = 4 * (frequency * 1000000 + 225000) / 32768;
  byte frequencyH = frequencyB >>8;
  byte frequencyL = frequencyB & 0XFF;
  Wire.beginTransmission(0X60);
  Wire.write(frequencyH);
  Wire.write(frequencyL);
  Wire.write(0xB0);
  Wire.write(0x10);
  Wire.write(0x00);
  Wire.endTransmission();
}

void setup() {
  Wire.begin();
  setFrequency(f);
}

void loop()
{
}


texts: What are the benefits or advantages of Arduino CLI?

texts:
I saw that Arduino got a CLI (Command Line Interface), and my first question was "why?"  Even after reading the article, I don't see or understand its advantages.

What advantages or benefits does a CLI have for Arduino?

I haven't done much with Arduino in several years.  For example, there wasn't an Arduino SE when I was fooling around with Arduino, so I probably have an out of date context for Arduino development.


texts: Parsing array of an object in a library constructor

texts:
I am trying to develop an Arduino library that consists out of two classes. I want 'WayPointStack' to store an array of 'WPCommand', but I can't get it to work.

WayPointStack.h

#ifndef WayPointStack_h
#define WayPointStack_h

#include "Arduino.h"
#include "WPCommand.h"

class WayPointStack
{
  public:
    WayPointStack();
    WayPointStack(WPCommand* wp);
    WPCommand GetNextWP();
    WPCommand GetWP(int i);
    void AddWP(int target, int time);
    int SetWPPointer(int i);
    int GetLength();
  private:
    WPCommand* _wp;
    int pointer;
    int length;
};
#endif

WPCommand.h

#ifndef WPCommand_h
#define WPCommand_h

#include "Arduino.h"

class WPCommand
{
  public:
    WPCommand(int target, int time );
    WPCommand();
    int GetTarget();
    int GetTime();
    int LEFT;
    int RIGHT;
    int FORWARD;
    int BACKWARD;
    int STOP;
    int END;
  private:
    int _target;
    int _time;
};

#endif

Parts of WaypointStack.cpp

#include "Arduino.h"
#include "WayPointStack.h"
#include "WPCommand.h"

#define arrSize 100

WayPointStack::WayPointStack()
{
  _wp = new WPCommand[arrSize]; // should be enough, heap blabla
  length = 0;
  pointer = 0;
}

WayPointStack::WayPointStack(WPCommand[] wp)
{
    _wp = new WPCommand[arrSize]; // should be enough, heap blabla
    for (int i = 0; i < sizeof(wp), i++){
        _wp[i] = wp[i];
    }
    length = sizeof(wp);
    pointer = 0;
}

I'm pretty sure I'm doing something wrong with the pointers, but I don't know how to fix it. The first two errors are

WayPointStack.cpp:24:42: error: expected ',' or '...' before 'wp'
WayPointStack::WayPointStack(WPCommand[] wp)

and

WayPointStack.cpp:27:29: error: 'wp' was not declared in this scope
for (int i = 0; i < sizeof(wp), i++){

I obviously have to use a pointer. This is all I know, so far.
Has someone an idea?


texts: Difference between FreeRTOS libary (AVR_ATmega328PB_Xplained_mini_GCC) Versus FreeRTOS compatible for Arduino boards from Richard barrey

texts:
I am researching about different IoT development boards and found that espressif uses IDF framework. When looked at the source code it uses FreeRTOS libraries. I have Arduino Uno and i wanted to use FreeRTOS for programming Arduino Uno. After search i found that FreeRTOS has multiple libraries that supports different micro controllers. Arduino Uno has ATMega328P and FreeRTOS has libraries for ATMega328P (link below)
https://github.com/FreeRTOS/FreeRTOS/tree/master/FreeRTOS/Demo/AVR_ATmega328PB_Xplained_mini_GCC
I also found that libraries created for Arduino family of boards (link below)
https://www.arduino.cc/reference/en/libraries/freertos/
I just wanted to what is the difference between these two libraries?


texts: PIR sensor code logic works on Mega but not on Yún

texts:
I am trying to use this example(it works on Arduino Mega): millis() - lowIn comes greater than 5000when motion ends.

/////////////////////////////
//VARS
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 30;

//the time when the sensor outputs a low impulse
long unsigned int lowIn;

//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;

boolean lockLow = true;
boolean takeLowTime;

int pirPin = 3; //the digital pin connected to the PIR sensor's output
int ledPin = 13;

/////////////////////////////
//SETUP
void setup() {
  Serial.begin(9600);
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);
  digitalWrite(pirPin, LOW);

  //give the sensor some time to calibrate
  Serial.print("calibrating sensor ");
  for (int i = 0; i < calibrationTime; i++) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println(" done");
  Serial.println("SENSOR ACTIVE");
  delay(50);
}

////////////////////////////
//LOOP
void loop() {
  if (digitalRead(pirPin) == HIGH) {
    digitalWrite(ledPin, HIGH);
    //the led visualizes the sensor's output pin state
    if (lockLow) {
      // makes sure we wait for a transition to LOW before any further output is made:
      lockLow = false;
      Serial.println("---");
      Serial.print("motion detected at ");
      Serial.print(millis() / 1000);
      Serial.println(" sec");
      delay(50);
    }
    takeLowTime = true;
  }

  if (digitalRead(pirPin) == LOW) {
    digitalWrite(ledPin, LOW);
    //the led visualizes the sensors output pin state
    if (takeLowTime) {
      lowIn = millis();
      //save the time of the transition from high to LOW
      takeLowTime = false;
      //make sure this is only done at the start of a LOW phase
    }
    //if the sensor is low for more than the given pause,
    //we assume that no more motion is going to happen
    Serial.print(millis() - lowIn);
    Serial.print("    ");
    Serial.print(lockLow);
    Serial.print("    ");
    Serial.println(pause);
    if (!lockLow && millis() - lowIn > pause) {
      //makes sure this block of code is only executed again after
      //a new motion sequence has been detected
      lockLow = true;
      Serial.print("motion ended at "); //output
      Serial.print((millis() - pause) / 1000);
      Serial.println(" sec");
      delay(50);
    }
  }
}

But it doesn't work on a Yún shield mounted on an Arduino Leonardo. The difference of millis() - lowIn always comes out to be lower than pause.


texts: Can I use the nRF8001 Bluefruit LE Breakout on 3.3V instead of 5V on my Arduino Uno?

texts:
I have an nRF8001 Bluefruit LE Breakout module and when I check images on how to wire it, the schematic looks like this with the 5V connection:

I was wondering whether it was possible to use the 3.3V instead. I looked at the documentation, it says this:

  By connecting 5.0V on the VIN pin, all of the signals will be level shifted between 5V for the Arduino and 3.3V for the nRF8001, meaning you don't need to worry about damaging the IC by providing logic levels that it can't safely handle.

And this, which confirms that it works, right?

  If you are using 3.3V logic, simply connect 3.3V from your development board to the VIN pin on the nRF8001 breakout.

I am pretty new, so I want to make sure, so I do not destroy any modules.

https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/hooking-everything-up


texts: Serial ports(in 1.0.5 & Port in 1.6.11) is greyed out under tools

texts: I am running a linux distro on my pc(Ubuntu 16.04). I have installed Arduino IDE(version 1.0.5 since it's the only one available on the store) from the Ubuntu Software Center and also using the .ZIP file from the official Arduino website(version 1.6.11). When I ran IDE(1.0.5) the "Serial Port" drop-down was greyed out. Next ran the IDE(1.6.11) and again the "Port" drop-down under Tools was greyed out. I have spent hours looking online for a solution but all in vain. A tried and tested working solution will be highly appreciated.


texts: what voltage level is a digital low for the interrupt mode LOW?

texts:
I am learning about interrupts and one of the interrupt modes is LOW which triggers anytime the pin is a digital low.
Can someone tell me what voltage that is for an Arduino nano? I did a google search and it said a LOW can be anywhere from 0 to 2V.
I am making a project using a nano and I am powering it with batteries. It would be great if I could set up an interrupt to turn on an LED when the batteries were getting weak so I would know when to change them.


texts: I will start by saying I am very new to using Arduino.  The project I am planning is to create several arrays of sensors (each array will consist of 4 DS18B20 sensors and one temperature/humidity sensor) and using a MUX connected to Arduino I want to read the data from each [ten] array.  I have found sketches I can modify to do this task in a continuous cycle but I need to be able to display data from an array for an extended time period of several minutes.  My Arduino will output to a 3.2" LCD so there is only enough screen space to show data for one array at a time.


texts:
I am trying to send integer from my Python program to Arduino MEGA.
If I send 1, the LED should turn on and If  I send 0 the LED should turn off.

I was able to write Python code correctly as I think. I have configure the port and made serialWrite(val) function for send data to Arduino only if data is changed.
This not a full program. It has while loop. So, it writes data to Arduino rapidly. I used serialWrite(val) function to prevent that.

But, the LED never turns off, if I send 0. It turns on only. What are the problems in my code?

import serial as ser

prt = ser.Serial(
port='COM3',
baudrate=9600,
parity=ser.PARITY_NONE,
stopbits=ser.STOPBITS_ONE,
bytesize=ser.EIGHTBITS
)

preSerVal=0
#function for send data..data will send only val is changed
def serialWrite(val):
    global preSerVal
    if(not preSerVal == val):
        prt.write(str(val)+'\r\n')
        preSerVal=val

This is my Arduino program.

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}
byte incomingByte;

void loop()
{
  if (Serial.available() > 0) {
    incomingByte = Serial.read();
      if (incomingByte == '1') {
        digitalWrite(13, HIGH);
    } else if (incomingByte == '0') {
        digitalWrite(13, LOW);
    }
  }
}

UPDATE 1

I write testing program like this.

Python code:

import serial as ser
import time

preSerVal=0
prt = ser.Serial(
port='COM3',
baudrate=9600,
parity=ser.PARITY_NONE,
stopbits=ser.STOPBITS_ONE,
bytesize=ser.EIGHTBITS
)
def serialWrite(val):
    global preSerVal
    if(not preSerVal == val):
         prt.write(str(val)+'\r\n')
         preSerVal=val

while 1:
   for i in range(0,10):
        serialWrite(0)
   time.sleep(1)
   for i in range(0,10):
        serialWrite(1)

Arduino code:

void setup() {
 Serial.begin(9600);
 pinMode(13, OUTPUT);
 digitalWrite(13, LOW);
}
byte incomingByte;

void loop()
{
  if (Serial.available() > 0) {
    incomingByte = Serial.read();
  if (incomingByte == '1') {
    digitalWrite(13, HIGH);
  } else if (incomingByte == '0') {
    digitalWrite(13, LOW);
  }
 }
}

This code gives this result.
see the video bellow:

https://www.youtube.com/watch?v=utC4vo8YDVU&list=PLM5AA5oFchgC25da44Q2X900pz0eojSQJ&index=1

UPDATE 2

This is a piece of code..it sends 0..i checked it.

try:
    circles = np.uint16(np.around(circles))
    for i in circles[0,:]:
        houghCenter=(i[0],i[1])
        cv2.circle(src,houghCenter,i[2],(0,255,0),2)
        cv2.circle(src,houghCenter,2,(0,255,255),1)
        cv2.circle(drawing,houghCenter,i[2],(0,255,0),2)
        cv2.circle(drawing,houghCenter,2,(0,255,255),1)
        #print (houghCenter,"   ",contourCenter)
        dx=math.fabs(houghCenter[0]-contourCenter[0])
        dy =math.fabs(houghCenter[1]-contourCenter[1])
        if (dx>diff and dy>diff):
            serialWrite(0)
        else:
            serialWrite(1)
except Exception:
    serialWrite(0)


texts:
I have a question about arrays in Arduino. Sorry for my bad English.
I want to put numbers in an array, and I think the code below works properly.

However, it doesn't work and corrupted numbers show up in the Serial monitor. Even delay(1000) doesn't work.

If I change ND_MAC[i]=128; to "ND_MAC[i]=126;", it works properly. So I'm wondering if this array is char type, but I designate int to array.
How to solve it?

int ND_MAC[7];
char i=0;
void setup() {
  Serial.begin(9600);
}
void loop() {
  for(i=0;i<8;i++){
    ND_MAC[i]=128;
    Serial.print(ND_MAC[i],HEX);
  }
  Serial.println();
  delay(1000);
}


texts:
I made a circuit where when I press a button, a LED lights up using a pull-down resistor. But when I tried the same with a pull-up resistor instead, the LED remains off (whereas I expected it to be on by default and go off when I push the button). What is the problem?
Here is the circuit:

And here the code:
int BUTTON = 7;
int LED = 8;

void setup()
{
  pinMode(BUTTON, INPUT);
  pinMode(LED, OUTPUT);
}

void loop()
{
  digitalWrite(LED, digitalRead(BUTTON));
}


texts: How to read a Text file from server and store to a separate variable?

texts:
I am working on reading a text file from the server, using http://arduino.cc/en/Reference/GSMClientConnected. It gives me this code:

char path[]="/asciilogo.txt"

I want to store only the contents that are inside the text file to a variable (String). But client.read(); only reads a single character at a time. Also, it takes all the HTTP, GET, TIME parameters together.

How to store only the contents that are present in the text file to a string variable?


texts:
I am trying to update values to Firebase. According to Firebase:

curl -X PUT -d '{ "first": "Jack", "last": "Sparrow" }' \
  'https://[PROJECT_ID].firebaseio.com/users/jack/name.json'

We can update using put command. Using curl works fine, but when I look at the header of ESP8266HTTPClient, I don't see any put or patch method there.

I can only see the following:

int GET();
int POST(uint8_t * payload, size_t size);
int POST(String payload);

Whereas in NodeMCU documentation, it is clearly stated it supports the put method too.

http.put(url, headers, body, callback)

http.put() documentation

I cannot find any example.

How can I implement the put method in NodeMCU?


texts:
I'm quite a beginner at electronics, but thought I would try venture into it.
Currently I'm working on a project where I need to reuse a button module salvaged from some old hardware, but I can't figure out the wiring. The attached image is what I was able to track down on how the circuit is built. I'm not really sure how to wire it? Would it be possible to use this with an ESP32 and differentiate all the buttons?


texts:
I am running the following sketch on an Arduino Uno using Arduino 1.6.8.
Strip is a WS2811 12V.

#include <Adafruit_NeoPixel.h>
#define PIN 6
Adafruit_NeoPixel strip = Adafruit_NeoPixel(30, PIN, NEO_GRB + NEO_KHZ800);

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

void loop (){
   strip.setPixelColor(0, 255, 0, 255);
   strip.show();
}

The problem is that the LED’s light in (Green) groups of three and what I want is individual control.

strip.setPixelColor(0, 255, 0, 255); Illuminates Pixels 0,1,2
strip.setPixelColor(1, 255, 0, 255); Illuminates Pixels 3,4,5
strip.setPixelColor(2, 255, 0, 255); Illuminates Pixels 6,7,8

And so forth.

Although this code uses NeoPixel I get exactly the same issue if I use the equivalent in FastLed.

Any pointers to what I am doing wrong would be appreciated.


texts:
I was reading a tutorial on timers. My aim is to generate 16MHz pulse output from the pin 8.

Here is the code I modified from the tutorial (I use Arduino's ATmega328P):

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

int main (void)
{
    DDRB |= (1 << 0); // Set LED as output
    TCCR1B &= ~(1 << CS11); // Set up timer
    TCCR1B &= ~(1 << CS12); // Set up timer
    TCCR1B |= (1 << CS10); // Set up timer

    for (;;)
    {
        // Check timer value in if statement
        if (TCNT1 >= 0)
        {
            PORTB ^= (1 << 0); // Toggle the LED
            TCNT1 = 0; // Reset timer value
        }
    }
}

I use the following formula:

  Target Timer Count = (1 / Target Frequency) / (1 / Timer Clock
  Frequency) - 1

So Target Timer Count = 0 in my case.

But I get 615kHz on scope.

My timer setting should output 16MHz since I use no prescaler:

What am I doing wrong?


texts: Lighting up long led strip no longer works when my code grows

texts:
I have a 144 LED strip - Adafruit NeoPixel Digital RGB LED Strip 144 LED, link here:  https://www.adafruit.com/product/1507

If I create a simple project, eg turning pixels on off from the serial connection, then everything works fine.  But when I build a solution with an ethernet jack and acting as a http server and lots more code, as soon as I try to show the strip then random pixels light up in random colours.

I know the code is logically ok because if I run it to eg print a string to the serial port, "Turning pixels 0-71 green" the code works.

There are 762 lines of code and quite a few global variables defined.

When I compile I see:

Sketch uses 19180 bytes (59%) of program storage space. Maximum is 32256 bytes.
Global variables use 1462 bytes (71%) of dynamic memory, leaving 586 bytes for local variables. Maximum is 2048 bytes.

I did previously see build messages warning of instability due to size of global variables which I cut down and at least don't see the instability warning now.  Could it be that the code is using too many resources?  Any tips of reducing the code and / or use of global variables?

I am powering via the USB cable.  The unit is an Arduino Uno -the Arduino starter kit.  Could it be a power issue?

I have a 470ohm resistor on the data line into pin 6.  And a 1000uF capacitor between 5V+ and ground.  Anything else that could help?

I am using the Neopixel library to control the led strip: https://github.com/adafruit/Adafruit_NeoPixel


texts: Modbus RTU controller monitoring with arduino and RS485 module

texts:
I'm a medium user in Arduino. I baught a pHmeter controller with RS485 output (MODBUS RTU protocol).
I want to get pH value read by the controller over RS485 module and Arduino.
According the controller's manufacturer, we should operate as bellow:
Sent by computer : 00 03 00 00 00 01 85 DB
Return from controller : 00 03 02 02 AE 05 58.

#include SoftwareSerial.h

#define SSerialRX        10  //Serial Receive pin
#define SSerialTX        11  //Serial Transmit pin
#define SSerialTxControl 3   //RS485 Direction control
#define RS485Transmit    HIGH
#define RS485Receive     LOW
#define Pin13LED         13

SoftwareSerial RS485Serial(SSerialRX, SSerialTX); // RX, TX
byte byteSend;

void setup()
{
  // Start the built-in serial port, probably to Serial Monitor
  Serial.begin(9600);
  Serial.println("SerialRemote");  // Can be ignored

  pinMode(Pin13LED, OUTPUT);
  pinMode(SSerialTxControl, OUTPUT);

  digitalWrite(SSerialTxControl, RS485Receive);  // Init Transceiver

  RS485Serial.begin(9600);
  delay(2000);
  digitalWrite(SSerialTxControl, RS485Transmit);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x03);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x00);
   RS485Serial.write((byte)0x01);
   RS485Serial.write((byte)0x85);
   RS485Serial.write((byte)0xDB);
   Serial.println(" ");

   digitalWrite(Pin13LED, LOW);
   delay(10);
   digitalWrite(SSerialTxControl, RS485Receive);

}
void loop()
{

  if (RS485Serial.available())
  {
    byteSend = RS485Serial.read();   // Read the byte
    Serial.print(byteSend, HEX);
    Serial.print(" ");
  }
}

I tried this following sketch who does not work.
I would like to know if it is the good way to send request to the controller?


texts:
I came across something strange while reading the datasheet for the microcontroller in the Arduino Uno board.

It is the (8) note in pg.296-297 of this datasheet: what does WORDS mean in that context?