texts: How to connect a simple wall switch to arduino GPIO

texts:
I am trying to create a smart doorbell, but my problem is that doorbell makes ring any time when nobody touch the button.

I think that the problem is caused for the incorrect way to connect the analog wall button to arduino GPIO.

Basically my wiring diagram is:

Analog Input (A0) to 1 pin of the button.
Ground of the Arduino (GND) to the other pin of the button.

When the button is pressed, the circuit is closed, and doorbell makes ring!

But surely this is not the way to connect a button on the wall because the doorbell sounds on its own.

I leave a picture of the button


texts: 2D Tracking of an object - which sensor?

texts:
I'm currently working on a project for which I require a sensor. I've made a quick and simplified drawing of what the result is supposed to do:

Basically, I want one LED of a LED-Strip to light up dependent on the location of a moving object. If the object in above image (say a slow rolling ball) were to move from bottom to top, then the LED strip should also light up from bottom to top. I have no problem getting the LED strip to light up adequately, however I'm not sure which sensor actually can pick up objects as required in this case.

As I've understood regular IR sensors can only detect if there is an object and how far it is away, however they can't pick up said object's relative position on the y-axis. Is there any way to do this rather easily, perhaps with triangulation? I've looked into Bluetooth and RFID but haven't found anything particularly useful.


texts: How to use ESP8266 wifi shield as a hotspot?

texts:
I have bought a ESP8266 wifi shield and I want to use it hotspot, I have tried the examples that have been provided in Arduino IDE, and the shield is getting connected to my network and giving me a wifi but without internet access (like I can connect my phone to the shield but I cannot browse the internet).
Any suggestion please?

Thanks......


texts: Starting usb on pro micro after deep sleep (ATmega32u4)

texts:
I have just started playing with a low power arduino project, and have managed to get the power drain down to about 220uA using powerDown from LowPower.

What I would love to be able to do is start the USB controller and send some data every 8 seconds, but I cant seem to send anything...

Any idea would be greatly appreciated :)

Her is my code:

// **** INCLUDES *****
#include <LowPower.h>

#include <avr/interrupt.h>
#include <avr/power.h>
#include <avr/sleep.h>
#include <avr/io.h>

void setup()
{
  DDRD = B00100000;       // PORTD5 = TXLED
  DDRB = B00000001;        // PORTB0 = RXLed

  Serial.begin(9600);
  while (!Serial) ; // Needed for Leonardo only
  Serial.println("Starter...");
  delay(100);
  Serial.end();

  /*
  *  IKKE FJERN DENNE!!! Da greier vi ikke å omprogramere kortet...
  */
  delay(10000);
  Serial.begin(9600);
  while (!Serial) ; // Needed for Leonardo only
  Serial.println("low-power...");
  delay(100);
  Serial.end();
  flash();
}

void loop()
{
  //LowPower.idle(SLEEP_8S, ADC_OFF, TIMER4_OFF, TIMER3_OFF, TIMER1_OFF, TIMER0_OFF, SPI_OFF, USART1_OFF, TWI_OFF, USB_OFF);//, USB_OFF);
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
  //USBCON &= B11011111; //Disable USB Freeze clock USBCON.FRZCLK
  //USBCON |= B10010001; //SET USB_MACRO_ENABLE_BIT USBCON.USBE

    PLLCSR |= B00000010;   //-Enable             PLL PLLCSR.PLLE = 1;
    while (!(PLLCSR & 1)); //-Wait PLL LOCK      while (PLLCSR.PLOCK != 1);
    USBCON &= B11011111;   //-Unfreeze USB clock USBCON.FRZCLK = 0; (Clear to unfreeze)
    //-Clear Resume information ???

  flash();

  /*
  * Test USB kommunikasjon :)
  */
  Serial.begin(9600);
  while (!Serial);
  delay(5);
  Serial.println("Hello world!!!");
  delay(5);
  Serial.end();
   PORTD |= B00100000;
   PORTB |= B00000001;
}

void flash() {

   PORTD &= B11011111;
   PORTB &= B11111110;
   delay(100);
   PORTD |= B00100000;
   PORTB |= B00000001;
   delay(100);

   PORTD &= B11011111;
   PORTB &= B11111110;
   delay(100);
   PORTD |= B00100000;
   PORTB |= B00000001;
   delay(100);

   PORTD &= B11011111;
   PORTB &= B11111110;
   delay(100);
   PORTD |= B00100000;
   PORTB |= B00000001;
   delay(100);
}

Best regards, Richard

EDIT

The manual specifies this resume protocol:
Resuming the USB interface (21.13 USB Software Operating Modes)

Enable PLL
Wait PLL lock
Unfreeze USB clock
Clear Resume Informtion

which I have translated into this:

PLLCSR |= B00000010;   //-Enable             PLL PLLCSR.PLLE = 1;
while (!(PLLCSR & 1)); //-Wait PLL LOCK      while (PLLCSR.PLOCK != 1);
USBCON &= B11011111;   //-Unfreeze USB clock USBCON.FRZCLK = 0; (Clear to unfreeze)
//-Clear Resume information ???

It have no effect whatsoever, have no idea how to clear resume information though...

Also, for the record, the LEDs are flashing happily every 8 seconds.


texts: How is interaction with CDC device with no interface endpoints working?

texts:
I'm working on uploading to Digispark board. It uses micronucleus bootloader and i can see uploader code. I've modified it a bit to see interfaces and endpoints count:

    nucleus->device = usb_open(dev);

    // added by me - start
    int interfaces, endpoints, j;
    struct usb_interface_descriptor *interface = NULL;

    interfaces = dev->config->bNumInterfaces;
    fprintf(stderr, "Found interfaces: %i\n", interfaces);

    interface = &(dev->config->interface[0].altsetting[0]);
    fprintf(stderr, "Endpoints: %i\n", interface->bNumEndpoints);
    // added by me - end

    // get nucleus info
    unsigned char buffer[4];
    int res = usb_control_msg(nucleus->device, USB_ENDPOINT_IN| USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, 0, (char *)buffer, 4, MICRONUCLEUS_USB_TIMEOUT);

I wonder how it's working because interface #0 has no endpoints:

$./micronucleus --type intel-hex /tmp/Start.ino.hex
> Please plug in the device ...
> Press CTRL+C to terminate the program.
Found interfaces: 1
Endpoints: 0
> Device is found!
connecting: 40% complete
> Device has firmware version 1.6
> Available space for user applications: 6012 bytes
> Suggested sleep time between sending pages: 8ms
> Whole page count: 94  page size: 64
> Erase function sleep duration: 752ms
parsing: 60% complete
> Erasing the memory ...
erasing: 80% complete
> Starting to upload ...
writing: 100% complete
>> Micronucleus done. Thank you!

Usually i expect interface to have 2 endpoints (in & out from usb.h):

#define USB_ENDPOINT_IN         0x80
#define USB_ENDPOINT_OUT        0x00

Can anyone explain me how usb_control_msg(nucleus->device, USB_ENDPOINT_IN| USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, 0, (char *)buffer, 4, MICRONUCLEUS_USB_TIMEOUT); is working without endpoint?


texts:
I want to use Arduino as my RC receiver. I will generate PPM signal from Arduino. Then I will send generated signal to my OpenPilot CC3D. I fetched following image from OpenPilot GCS. The diagram shows to use input 6.

Following is the image of my CC3D. The cable colors does not correspond to each other.

Which input cable should I connect to Arduino?
How should I connect black(ground) and red(5V) cables to Arduino:


texts: "SparkFun SAMD21 Mini Breakout" 'Serial1' was not declared in this scope

texts:
I recently switched computers and installed Arduino IDE, Added SAMD21 to the boards manager and installed drivers.
My sketch previously ran on my laptop with no problems.  Now when I try to compile for the SAMD21 Mini, I get a 'Serial1' was not declared in this scope error.
If I try to compile it for Mega, there are no problems.
I have tried sample code with Serial1 for SAMD21 and it compiled and uploaded with no problems.


texts: Can SPI and serial.begin be used at the same time?

texts:
I have two modules where I want to control them through a single Arduino UNO.

I guess Serial.begin(9600) uses serial port and UART. But Im not sure about SPI.

Can I use SPI library hence the SPI communication together with serial communication(serial.begin) at the same time to communicate with two different modules?


texts: Communication between two Arduinos over RF module

texts: I want to communicate Arduino A to Arduino B by using RF module. But my RF module (Tx- XLPCF20, Rx- XY-R01A) only consist of 4 pins of data pin where it can send 4 bits of data only. So, I want to develop a new encoding to send data by using 4 bits of data. How should i do for the coding since I don't want to use serial write for coding. Any suggestion? Help me please. If u can give me the coding, I'm beyond thankful.


texts:
I am using a MAX6675 board and a k-type thermal couple to measure temp. The problem is even when running the example the temp value keeps climbing.

MAX6675 test
27.25
C = 27.25
F = 130.10
109.00
C = 218.00
F = 816.80
872.00
C = 1744.00
F = 2624.00
832.00
C = nan
F = nan
512.75
C = nan
F = nan

I am using the max6675.h library. Is there a way to fix this?

#include "max6675.h"

int thermoDO = 4;
int thermoCS = 5;
int thermoCLK = 6;

MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);
int vccPin = 3;
int gndPin = 2;

void setup() {
  Serial.begin(9600);
  // use Arduino pins
  pinMode(vccPin, OUTPUT); digitalWrite(vccPin, HIGH);
  pinMode(gndPin, OUTPUT); digitalWrite(gndPin, LOW);

  Serial.println("MAX6675 test");
  // wait for MAX chip to stabilize
  delay(500);
}

void loop() {
  // basic readout test, just print the current temp

   Serial.print("C = ");
   Serial.println(thermocouple.readCelsius());
   Serial.print("F = ");
   Serial.println(thermocouple.readFahrenheit());

   delay(1000);
}

edit: Added code (https://github.com/adafruit/MAX6675-library/blob/master/examples/serialthermocouple/serialthermocouple.pde)


texts:
I'll like to code for a game, and it'll come with a stop option that allows the player to exit/restart the game.

How should I code for that stop button? Do I put it in a separate while loop under the void loop?


texts: Code that worked in Uno/Nano is not working in Mega - help me port the code to Mega

texts:
I used the code from this project... to build an oscilloscope-like project. It worked fine with Uno and Nano.

Later I tried to do the same with a Mega, but I don't know what's wrong. It's not working! Maybe due to some pin or port number mismatch (I think so...). Because it has some low level code like:

------------------------------------------------------
// set up 8 MHz timer on pin 9
pinMode (9, OUTPUT);
// set up Timer 1
TCCR1A = _BV (COM1A0);  // toggle OC1A on Compare Match
TCCR1B = _BV(WGM12) | _BV(CS10);   // CTC, no prescaling
OCR1A =  0;       // output every cycle
---------------------------------------------------------

And like:

Data.Values[i]=PINC;

I have very little knowledge about these registers.

Please help me port this code to Mega and make it work...


texts:
I wish to use some PIR (HC-SR501) sensors and give some response if at least one of them detects human movements.
For simplicity I wish to use only one input pin in an Arduino UNO. My idea is to connect all the output wires into a single Arduino digital input. Should it work?
I am in doubt because the following two reasons:

The sensors must be far away from each other (about 5 sensors partially covering an area of about 200 m^2). That implies that wires are long and I do not know if this can have some adverse effect.
I do not know if it is bad to supply the 3.5V of some sensor that is currently detecting movement to the output of the sensors that are not detecting anything.

Thanks in advance


texts: LCD5110 - How to make Direct Draw via 2D-array of boolean?

texts:
How to draw 2D-array directly on LCD 5110 (PCD8544)?

I have tried libraries like AdaFruit and several others.

But I need draw there via pixel 2D-array, something like this:

bool picture[48][84] = {
 {0,1,0,0, ... to 84 elements},
 {1,0,1,0,0, ...},
 ... to 48 elements
};

I haven't used charset table or geometry figures drawing library functions. Simplest and smallest drawing by pixel - 0 - not draw, 1 - draw pixel.

The "picture bitmap" will generate on the mini-pc board via Python and send to Arduino, which will draw it as "video card".

What is the simplest way to draw pixel in any site of the display without using powerful libraries?

Something about this:

// Send boolean bitmap 48x84 to LCD 5110
// Rows
for (int i=0; i<48; i++) {
 // Columns
 for (int j=0; j<84; j++) {
  // PIN 5 is Din on the 5110 module
  digitalWrite(5, picture[i][j]);
 }
}


texts:
I am an electronics graduate and an embedded design engineer, working in this field for about two years apart from the hobby time during my graduation. I am currently working on a system that has an Atmega2560 as the core controller with an arduino bootloader, we are using an 8GB memory card to save the log data from our system and send it to our server at regular intervals of time. The system worked fine however some of them are facing issues with the writing of data, some garbage value are getting stored in the SD card. I have attached the schematic and code snippet for the same, please let me know if there is any problem with the system and how can i resolve it, please let me know if any other things are required for understanding the problem correctly.

Thank you in advance.

     SD_Initialize();
  if(!SD.exists(SDTransactionDirectory))
  {
    if(SD.mkdir(SDTransactionDirectory))
    {

    }
  }
  RTC_Date_Time();
  String FileName = SDTransactionDirectory + "/" + RTCSDDate + RTCSDTime + ".txt";
  SD_File = SD.open(FileName, FILE_WRITE);
  if(SD_File)
  {
    delay(100);
    digitalWrite(LED_SD, HIGH);
    SD_File.println(GSMData);
    SD_File.close();
  }

The SD_Initialize() is a user function:-

void SD_Initialize()          //initialise SD card
{
  digitalWrite(SD_EN, HIGH);
  digitalWrite(SD_CS, LOW);

  delay(500);

  if(SD.begin(SD_CS))
  {
    digitalWrite(LED_SD, HIGH);
  }
  else
  {
    digitalWrite(LED_SD, LOW);
  }
}

The data stored in the filename is as follows:-
CLEnT|T|M008|\00Ÿûmï°]ŸëÜ£·zoòTÏæ{Œü[ŸýUô~ÛcCWY®ÞgÙë×<;wBÄgnìÇFÿÉ=XoÎ.êžÄf·®ö¯³ç~åeÝ]1_ÏÀyÿÌÍ?ô"zBõ¬ñ

As you can see the initial values till "M008" is fine but its garbage after that, and the CLEnt|T|M008 is the start of the string after that a lot of other parameter information is to be stored which turns out to be garbage.


texts:
I was trying to interface my hex keypad with Arduino. I declared rows as input and columns as output. When I initialize three of the four columns as HIGH and one as LOW, and detect the button pressed as LOW in the corresponding row, it works fine. That is, it detects the button when its corresponding row and column is LOW. But, when I reverse the condition, i.e. when I try to detect the button pressed when its corresponding row and column is high while others are low, it does not work as expected.

I really want to know why is this happening?

The code that works:-

int row[]={6,7,8,9};
int col[]={10,11,12,13};
int i,j;
int col_scan;
void setup()
{
   Serial.begin(9600);
   for(i=0;i<=3;i++)
   {
      pinMode(row[i],OUTPUT);
      pinMode(col[i],INPUT);
      digitalWrite(col[i],HIGH);
   } }
void loop()
{
   for(i=0; i<=3; i++)
   {
      digitalWrite(row[0],HIGH);
      digitalWrite(row[1],HIGH);
      digitalWrite(row[2],HIGH);
      digitalWrite(row[3],HIGH);
      digitalWrite(row[i],LOW);
      for(j=0; j<=3; j++)
      {
     col_scan=digitalRead(col[j]);
     if(col_scan==LOW)
     {
        keypress(i,j);
        delay(300);
     }}
   }}
void keypress(int i, int j)
{
   if(i==0&&j==0)
      Serial.println("1");
   if(i==0&&j==1)
      Serial.println("2");
   if(i==0&&j==2)
      Serial.println("3");
   if(i==0&&j==3)
      Serial.println("A");
   if(i==1&&j==0)
      Serial.println("4");
   if(i==1&&j==1)
      Serial.println("5");
   if(i==1&&j==2)
      Serial.println("6");
   if(i==1&&j==3)
      Serial.println("B");
   if(i==2&&j==0)
      Serial.println("7");
   if(i==2&&j==1)
      Serial.println("8");
   if(i==2&&j==2)
      Serial.println("9");
   if(i==2&&j==3)
      Serial.println("C");
   if(i==3&&j==0)
      Serial.println("*");
   if(i==3&&j==1)
      Serial.println("0");
   if(i==3&&j==2)
      Serial.println("#");
   if(i==3&&j==3)
      Serial.println("D");
}

the code that doesn't work:-

int row[]={6,7,8,9};
int col[]={10,11,12,13};
int i,j;
int col_scan;
void setup()
{
   Serial.begin(9600);
   for(i=0;i<=3;i++)
   {
      pinMode(row[i],OUTPUT);
      pinMode(col[i],INPUT);
      digitalWrite(col[i],LOW);
   } }
void loop()
{
   for(i=0; i<=3; i++)
   {
      digitalWrite(row[0],LOW);
      digitalWrite(row[1],LOW);
      digitalWrite(row[2],LOW);
      digitalWrite(row[3],LOW);
      digitalWrite(row[i],HIGH);
      for(j=0; j<=3; j++)
      {
     col_scan=digitalRead(col[j]);
     if(col_scan==HIGH)
     {
        keypress(i,j);
        delay(300);
     }}
   }}
void keypress(int i, int j)
{
   if(i==0&&j==0)
      Serial.println("1");
   if(i==0&&j==1)
      Serial.println("2");
   if(i==0&&j==2)
      Serial.println("3");
   if(i==0&&j==3)
      Serial.println("A");
   if(i==1&&j==0)
      Serial.println("4");
   if(i==1&&j==1)
      Serial.println("5");
   if(i==1&&j==2)
      Serial.println("6");
   if(i==1&&j==3)
      Serial.println("B");
   if(i==2&&j==0)
      Serial.println("7");
   if(i==2&&j==1)
      Serial.println("8");
   if(i==2&&j==2)
      Serial.println("9");
   if(i==2&&j==3)
      Serial.println("C");
   if(i==3&&j==0)
      Serial.println("*");
   if(i==3&&j==1)
      Serial.println("0");
   if(i==3&&j==2)
      Serial.println("#");
   if(i==3&&j==3)
      Serial.println("D");
}


texts:
Attempting to make gps unit with screen. GPS unit communicates over serial (Adafruit Ultimate GPS Breakout) and I can get GPS data through USB to my pc with Adafruit GPS library softwareserial examples. The screen communicates over I2C (Sunfounder OLED-SSD1306 Module) and I can get display with Adafruit SSD1306 examples. However I cannot get both to happen simultaneously. Board is Adafruit Metro Mini 5v 16MHZ. GPS is using pin 8 for TX and pin 9 for RX. Display is using A4 for SDA and A5 for SCL.

If "Adafruit_GPS GPS(&mySerial);" is not commented the screen will not display anything. If it is commented the screen displays just fine. How do I get both to function simultaneously?

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET     -1
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8, 9);
Adafruit_GPS GPS(&mySerial);

void setup() {
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    for(;;);
  }
  display.display();
  delay(2000);
  display.clearDisplay();
  display.drawPixel(10, 10, SSD1306_WHITE);
  display.display();
  delay(2000);
  testdrawchar();
}

void loop() {
}

void testdrawchar(void) {
  display.clearDisplay();

  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.cp437(true);

  for(int16_t i=0; i<256; i++) {
    if(i == '\n') display.write(' ');
    else          display.write(i);
  }

  display.display();
  delay(2000);
}


texts: How can a function/method determine if a const array passed in is PROGMEM (flash) or not (RAM)?

texts:
Is it possible for a function/method to know if a constant array that has been passed in is in flash or RAM?

If I have a method or function that receives a constant array that is in RAM, the array is declared like this:  const uint8_t MY_ARRAY[] = { 1, 2, 3, 4 };

gets passed into a method or function like this:  MyFunction(MY_ARRAY);

and the method or function can handle it like this:

void MyFunction(const uint8_t *MY_ARRAY) {
     uint8_t secondElement = MY_ARRAY[1];
     ...

However, if the array is in Flash (because it's a constant array, so that's where it should go), then the declaration adds PROGMEM:   const uint8_t PROGMEM MY_ARRAY[] = { 1, 2, 3, 4 };

The pass looks the same:  MyFunction(MY_ARRAY);

And the function declaration looks the same but it needs to use pgm_read_byte_near to get the correct values back:

void MyFunction(const uint8_t *MY_ARRAY) {
     uint8_t secondElement = pgm_read_byte_near(MY_ARRAY+1);
     ...

How can the receiving method know if the array is in flash (PROGMEM) or RAM (no PROGMEM) so it knows to use pgm_read_byte_near or not?  Ideally I'd like a compiler error, but the type is the same (both are const arrays of uint8_t).

If pgm_read_byte_near is used when it shouldn't be, or it's not used when it should be, the results are garbage.

Some relevant questions:
How to pass a static const (progmem) array to a function

RAM usage question: PROGMEM vs const vs #define

Storing array in PROGMEM

PROGMEM: do I have to copy data from flash to RAM for reading?

UPDATE:
It looks like what I want to do is not possible.  The responses below are very interesting options though:  using __flash in plain C, using OOP to make PROGMEM and non-PROGMEM data holders or trying to (somehow?) use non-deprecated progmem specific data types from avr/gpmspace.h.

The best answer to my original question is that the method can not make this determination.  The best solution, from a comment by Delta_G, is to create regular (ram) and "_P" (flash/ progmem) versions of the functions and to be as obvious as possible in the naming of those functions.


texts: Distinguishing between multiple Infra Red Transmitters

texts:
I am working on an Arduino project where I use an infra red camera along with 4 transmitters placed each on a corner of a square platform to park a robot perfectly on this platform.
However, it is important for the camera to distinguish between the 4 transmitters.
(it should know the right transmitters from the left and the upper transmitters from the lower).
Can anyone please help me find a solution to this problem?


texts: Windows upload from command line gives Access Denied

texts:
saw somewhere that in order to upload a hex file to an arduino you can look at the Arduino IDE - see the command it runs, then replace the hex file with your file.
this is the command I see in the output window:
C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avrdude -CC:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\yossi\AppData\Local\Temp\arduino_build_696128/sketch_aug21a.ino.hex:i
I try running this from command (as admin):
cd "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin"
avrdude -CC:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\foosMaster\AppData\Local\Temp\arduino_build_696128/sketch_aug21a.ino.hex:i

gives me Access is denied.
in fact, just running avrdude gives the same error, so really - this has nothing to do with the COM port (which works fine from the IDE)
I tried closing the IDE and running again, tried rebooting - the same.
*** edit 1 ****
I actually ran this:
cd "C:\PROGRA~1\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin"
avrdude -CC:\PROGRA~1\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\foosMaster\AppData\Local\Temp\arduino_build_696128/sketch_aug21a.ino.hex:i

since I didn't want to mess with wrapping the params - but I don't really think it matters - as the problem is running avrdude without any parameter still gives me the same error: Access is denied.


texts:
Here is a code snipet for ultrasonic sensor

digitalWrite(trigpin,HIGH);
delayMicroseconds(10);
digitalWrite(trigpin,LOW);

duration=pulseIn(echopin,HIGH);

Assume trigpin and echopin pins are already defined.

Now according to Arduino reference guide pulseIn funcion:

  Reads a pulse (either HIGH or LOW) on a pin. For example, if value is HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in microseconds or 0 if no complete pulse was received within the time out.

So shouldn't I be getting 10 microseconds as my answer, since since initial state of echo pin is low, now when the reflected sound hits receiver, echo pin goes high, the timer gets started and when and when the pulse ends the echo pin goes low again and since pulse sent was of 10 microseconds of length, the ans should be 10, but any ultrasonic program I have seen uses this code to find the duration the ultrasonic wave takes since it gets emitted to the time it gets into the receiver.


texts: 2 buttons, 1 servo, turn when pressed only

texts:
I have a code problem. I need to turn a servo clockwise or counter clockwise using 2 microswitches.

The problem is that my code is fine on startup, but when i press the button the servo continues to spin.

How do i make this so it only spins while the buttons are pressed and turn off when they are not pressed?

#include <Servo.h>

Servo myservo; // create servo object to control a servo

// CONSTANTS

// PINS
const int crServo = 12; // sets pin 12 as servo
const int buttonPinCW = 2; // sets pin 2 as button; CW => clockwise => FOCUS FAR
const int buttonPinCC = 3; // sets pin 3 as button; CC => counterclockwise => FOCUS NEAR

// SERVO PROPERTIES
const int crSpeedDefault = 0; // is the stay still position, motor should not turn
const int crSpeedCW = 110; // turns the motor full speed clockwise
const int crSpeedCC = 70; // turns the motor full speed counter-clockwise

// SET BUTTON STATES
int buttonStateCW = 0; //sets button 1 as off
int buttonStateCC = 0; // sets button 2 as off

void setup()
{
  myservo.attach(crServo); // attaches the servo on pin 12 to the servo object
  pinMode (crServo, OUTPUT);
  pinMode (buttonPinCW, INPUT); // sets button as input
  pinMode (buttonPinCC, INPUT); // sets button as input
  myservo.write(crSpeedDefault); // default servo to crSpeedDefault
}

void loop()
{
  crServo = digitalRead(crSpeedDefault);
  buttonStateCW = digitalRead(buttonPinCW);
  buttonStateCC = digitalRead(buttonPinCC);
  // clockwise rotation
  if (buttonStateCW == HIGH) {
    myservo.write(crSpeedCW);
    // counterclockwise rotation
  }
  if (buttonStateCC == HIGH) {
    myservo.write(crSpeedCC);
  }
}


texts: How to toggle LED and motor on button press?

texts:
we want to have a LED turn on with the press of a button, and become brigther and brighter as times go by (whithin  a defined time frame), and when it reaches maximum brightness to turn off for a couple of seconds and then start again. in addition to that, we are trying to add a motor that will start spinning 720 degrees when the button has been pressed.
Our main problem is the fact that when we let go of the button the led turns off. How do we set the button so that when it is pressed once it turns everything on, and the led runs in a loop, but the motor doesn't; and when we press it again the whole led turns off completely and the motor runs 720 degrees in the opposite spinning direction than the previous.

Here is what we have managed so far (we didn't get to introduce the motor yet as we got stuck along the way):

const int switchPin = 11;
const int motorPin = 6;
int led = 9;
int switchState = LOW;
int previous = LOW;
int i = 0;
int fadeAmount = 5;

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

void loop()
{
  int switchState = digitalRead(switchPin);

  for (int i = 0; i <= 255; i++)
  {
    analogWrite(led, i);
  }

  if (switchState == HIGH && previous == LOW)
  {
    if (i == 0)
    {
      digitalWrite (led, HIGH);
      i = i + fadeAmount;
      delay(1000);
    }

    analogWrite(led, i);

    for (int i = 255; i <= 255; i--)
    {
      digitalWrite (led, LOW);
      i = 0;
    }
  }
  else
  {
    //toggle off
    digitalWrite(led, LOW);
    i = 0;
  }
}

PS. WE are beginers. Thanks for the help and understanding!


texts: How to read info from an Xbee Pro S2B to an Arduino with a Xbee Pro S2B

texts:
I am using two XBee Pro S2B modules. One (Router) connected to the laptop via a UART cable. The other (Coordinator) connected to an Arduino Mega with the sketch below.  All I need it to do is turn a LED on and off and display the status in the IDE serial monitor.  I am using Arduino IDE (v1.6.0).

Arduino sketch:

#include <SoftwareSerial.h>

SoftwareSerial xbee (2,3);

int myData = 0;
int ledPin = 13;

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

    pinMode(ledPin, OUTPUT);
}

void loop()
{
    if (Serial.available())
    {
         int myData = Serial.read();

         if(myData == '1')
         {
             digitalWrite(ledPin,HIGH);
             Serial.write(myData, DEC);
         }
         if(myData == '2')
         {
             digitalWrite(ledPin,LOW);
             Serial.write(myData, DEC);
         }
     }
 }

Where did I go wrong?


texts: So recently I have been looking into prototyping my arduino project and there are a lot of tutorials online on how to take your Arduino and using a software such as Eagle to make a PCB layout but I was wondering how you would get the Arduino program onto that PCB. Surely in large scale circuit manufacturing they wouldn't have a usb attached so that they upload a program into each and every one of their circuits?


texts: Powering up small motor board without motor

texts:
Looking to supply power to the middle rings of this board on the back. It takes 3v to power it up. I’ve tried soldering but it’s for a motor so I’m not sure if it can stay permanently. Is there any way to power this up? I have a coin battery that I hooked up and pressed onto the middle rings and it powered up but it’s not stable or permanent. No idea how to see if there I a pin or solder point I could power it to. Any help would be greatly helpful.
Thanks in advance.


texts: Reading an output analog pin with an input analog pin

texts:
I am having a hard time understanding why I can't read one analog pin's output with another analog pin. The docs state to put a delay in between, which I've done (I've tried up to one second with the same results). I've got this minimized code:

void setup() {
    Serial.begin(9600);
    pinMode(A0, INPUT);
    pinMode(A5, OUTPUT);
}

void loop() {
    for (int i=0; i<1024; i++){
      analogWrite(A5, i);
      delay(100);
      Serial.println(analogRead(A0));
    }
    Serial.println("done");
    delay(10000);
}

When it starts, it displays 6-9 for a few dozen iterations, then suddenly jumps to ~1018 and remains throughout the rest of the run.

A5 is connected directly to A0 via a 4" jumper cable. Nothing is connected to AREF. If I connect AREF to 5v, the output does not change but by a single digit. If I connect it to ground, it immediately outputs 1023.

I'm hoping this is a "do'h" moment here. Can someone please let me know what I'm not doing correctly?

Update: This is a legit Arduino Uno R3 board. When I connect A0 directly to 5v+, I get 1023 as expected as the output.


texts: All of the sudden the Nano will not accept programming

texts:
I have been working merrily along with CH340 to make Com10 work.  It has been working flawlessly but now I am getting various messages like it can't open the port then the programmer is not responding.  It tries several times before giving up.

This was working fine yesterday.

I tried uploading to a raw board not connecting to anything and am getting the same result.

Suggestions?


texts:
I'm currently designing a battery operated device that has to write data to an EEPROM before shutting down, or in regular intervals to save data. Would it damage the EEPROM if it had to shut down while it is being written to?

The first possible case is when it is transmitting the data over I2C. That shouldn't affect it much. But if it gets powered down while it is actually writing the byte to its memory, I don't know whether it would save it correctly or corrupt it.


texts: Sainsmart Omron 12V optocoupled 2 channel relay problem

texts:
I know that there are plenty of questions related to relays, but I have to ask. I am trying to sort out the issue and spend hours reading but cannot make progress.

I have SainSmart 2-Channel 12V Relay Module for Arduino and wired it according to picture.

Arduino UNO R3 board is powered from 12V plug external power supply. I take that 12V to power JD-VCC on relay (from VIN). Arduino 5V is used to power optocoupler circuitry.

I want to use to power 12/24/220V devices (on picture I wired 6V battery for troubleshooting).

So, when I set PIN7 to LOW i would expect that fan spins up. LED on relay goes RED, so I expect it is sign that relay is activated. However, fan does not power on.
When I bring PIN7 to HIGH, I hear click; LED goes OFF. I assume it deactivated relay. All the time I have 6V on voltmeter.

What I am doing wrong?
I really tried to find answer around, but either I do not see or it is not so obvious.

Thank you,


texts: Help managing the fallout from timer0 mode and prescaler change on ATMega2560 without modifying wiring.c

texts:
For a driving application I need the PWM mode to be phase correct and the prescaler to be 1. The issue is that the board I am working with has the load hooked up to a PWM pin reliant on timer0. The firmware running on this board makes use of the delay(), delayMicroseconds(), and millis() functions from wiring.c. The goal is to make the timer0 change, shown below, and then make small modifications where the firmware calls the wiring.c timing functions. My approach was to find a scaling factor to be applied to the call of these functions. The scaling factor I came to was 32.12549, calculated by taking the wiring.c expected timer0 behavior: prescaler=64 and TOV0 flag every 256 counts, and comparing it to the actual values after my change: prescaler=1 and TOV0 flag every 510 counts

Calculation: 64*256/510=32.12549

Timer0 change:

// Set timer0 to phase correct PWM
TCCR0A = TCCR0A & 0b11111100 | 0x01;

// Set prescaler for timer0 to 1
TCCR0B = TCCR0B & 0b11111000 | 0x01;

The other timers are all configured in phase correct PWM mode, with a prescaler of 1.

...When I apply this scaling factor to a value returned from millis() to keep time it works well. For example the two pieces of code below proved to be equivalent through the timer0 change:

Use of millis() before timer0 change:

//current time
long unsigned now = millis();

//delay for 1 second
while(millis() - now < 1000){}

Use of millis() after timer0 change:

//current time
long unsigned now = millis();

//delay for 1 second, with x32.125 scaling coefficient
while(millis() - now < 32125){}

The two snippets of code above both delayed for 1 second

Now comes the problem: when I try to apply that same scaling factor to delay() or delayMicroseconds() it seems to give unreasonable delays...

Use of delayMicroseconds() before timer0 change:

// wait 1.5ms for mux to switch
delayMicroseconds(1500);

...this delays for 1.5ms

Use of delayMicroseconds() after timer0 change:

// wait 1.5ms for mux to switch, with x32.125 scaling coefficient
delayMicroseconds(48188);

...this delays for ~20ms.

Assuming this is still linearly scalable:
 if 48188 -> 20ms, therefore 1.5ms -> 3614

But when the following code is used...

// wait 1.5ms for mux to switch, scaled
delayMicroseconds(3614);

...this delays for ~4.5ms

Why is it that delayMicroseconds() and delay() cannot be linearly scaled to account for a timer0 change? Furthermore, is there any simple modification to how these functions are called or utilized that can account for the effect of changing timer0?


texts: How to limit the number of message that an Arduino sends to a phone without terminating it

texts:
I just stayed on delay() since that is the only thing I know but the thing is delay() cannot be interrupted. What I'm trying to achieve with this code is:

When the soilSensor detects moisture it would send a text message to a number only ONCE without terminating the program even if in the next loop the soilSensor is still detecting moisture.
The soilSensor's delay is delay(60000) and we would still wait for while to finish the delay but what if in the middle of the soilSensor's delay(60000) there is a movement for just about 5 seconds? What to do so that the tiltSensor can overlap the soilSensor's delay and sends a message to a number?

I want this program to run forever. Please help me! I needed this ASAP!

#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);
int led=22;

void setup()
{
  Serial.begin(9600);
  SIM900.begin(19200);
  pinMode(led, OUTPUT);
  delay(1000);
}

void sendSMS1()
{
  SIM900.println("AT + CMGS = \"+************\"");
  delay(100);
  Serial.println("Water Detected");
  delay(100);
  SIM900.println("Water Detected");
  delay(100);
  SIM900.println((char)26);
  delay(100);
  SIM900.println();
  delay(100);
}

void sendSMS2()
{
  SIM900.println("AT + CMGS = \"+************\"");
  delay(100);
  Serial.println("Movement Detected");
  delay(100);
  SIM900.println("Movement Detected");
  delay(100);
  SIM900.println((char)26);
  delay(100);
  SIM900.println();
  delay(100);
}

void loop()
{
  int soilSensor = analogRead(A0);
  int tiltSensor = analogRead(A1);

  if(soilSensor >= 10)
  {
    digitalWrite(22, HIGH);
    Serial.println(soilSensor);
    sendSMS1();
    delay(60000);
  }
  else
  {
    digitalWrite(22, LOW);
    delay(60000);
  }

  if (tiltSensor >= 100)
  {
    digitalWrite(led, HIGH);
    Serial.println(tiltSensor);
    sendSMS2();
    delay(60000);
  }
  else
  {
    digitalWrite(led, LOW);
    Serial.println(tiltSensor);
    delay(60000);
  }
}


texts: Continuous voltage on IO Pins while 5V is not Connected?

texts:
i have a small project where i just sucessfully destroyed my frist of 5 Digisparks (Attiny85).

In the Picture you see the Cirucit. I have 2 Liion cells connected in series to get high enough voltage to step it down to constant 5V. To these 5V some Neopixels and a Digispark controller are connected which will set the color for the Neopixels. A0 and A1 measure the Voltage of the Cells to signal the user if the Voltage is to low so it can manually be switched of.
While prototyping it i didnt have the 10k resistors in there.
Now what happend: While connecting the cells after each other the Controllers LEDs already lit up with the Frist cell. I guess it was powered trough the A0 pin (again i didnt have the 10k resistor in there),  so i guess the internal IO Protection diodes conductet the voltage trough and this way the controller got damanged. Since this happend it wont turn on Anymore.
The problem: since i have really small space i cant use a multiple pole switch to also remove the voltage from the IO pins and therefore i will always have voltage von A0 and A1 while there is no 5V Supplyvoltage. I would guess that the Series resistance on the pin would be enough to Limit the current trough them and this way protect the controller from damange. But i dont really have experience with that and hope that you guys can give me some hints what could also be a problem or what could help :) I really dont want to destroy a second one xD
Thanks in advance and have a nice day :)


texts:
I am building an Arduino based flight controller for a quadcopter and have got it flying but it is not performing how I want it to. The drone is flying but when I release the sticks the drone does  not stay perfectly still. There is some random and small oscillations that occur when it is just hovering.

Right now I am using a single PID controller for each axis though functions like this.

dt=0.005;
error = *in - *set;

P = (error * kp);
I = I + (error * ki)*dt;
D_M = ((*in - in1)*kd)/dt;
D_E = ((error - error1)*kd)/dt;
D=D_M*(1-jerk) + D_E*(jerk);

I = constrain(I, LOWER_BOUND*0.75, UPPER_BOUND*0.75);
in1 = *in;
error1 = error;
pid = P + I + D;

pid = constrain(pid, LOWER_BOUND, UPPER_BOUND);
*out = pid;

The error is the Euler angle and the setpoint is the angle I want it to go to.

I then output the PID controller values to the motors using the Arudino Servo library.

  motor1 = throttle;
  motor2 = throttle;
  motor3 = throttle;
  motor4 = throttle;

  motor1 += rollOUT;
  motor2 += rollOUT;
  motor3 -= rollOUT;
  motor4 -= rollOUT;

  motor1 -= pitchOUT;
  motor2 += pitchOUT;
  motor3 -= pitchOUT;
  motor4 += pitchOUT;

  motor1 += yawOUT;
  motor2 -= yawOUT;
  motor3 -= yawOUT;
  motor4 += yawOUT;

Is there something I am missing about quadcopter PID controllers? Thank you for the help!


texts: Problems recycling c++ lib with templated class for Arduino

texts:
I have a header & cpp file located in Arduino\libraries\Parentfolder\Header&Cpp. Arduino IDE recognizes my lib (the class is color coded & Sketch->include library->MyLibrary shows in the dropdown menu and #includes properly).

Problem: Arduino IDE gives undefined reference to MyClass . . . error in my sketch for every reference of the class including function calls. The function fully in other IDEs as header/cpps so I don't think pasting the cody is necessary -- what could I be missing? I've read a million Stack Exchange posts with similar error/watched a million YouTube guides on writing Arduino libs and I can't seem to find the differentiating factors that would make my code not work for Arduino IDE.

tl;dr what are the reasons that a working c++ library (self-made) would not work with Arduino IDE?

/e

Queue.h
#ifndef Queue_h
#define Queue_h

#include "Arduino.h"

template <typename T>
class Queue
{
  public:
    typedef struct node
    {
      T data;
      node * next = nullptr;
    } * nodePtr;

    nodePtr head; // = nullptr;
    nodePtr tail; // = nullptr;
    nodePtr curr; // = nullptr;
    nodePtr temp; // = nullptr;

    unsigned int counter;

    Queue();
    void push(T);
    T& peek();
    T pop();
    int size();
    bool isEmpty();
    void clear();
};

#endif

Queue.cpp

#include "Arduino.h"
#include "Queue.h"

template <typename T>
Queue<T>::Queue()
{
    nodePtr head = nullptr;
    nodePtr tail = nullptr;
    nodePtr curr = nullptr;
    nodePtr temp = nullptr;

    counter = 0;
}

template <typename T>
void Queue<T>::push(T data)
{
  if (head == nullptr)
  {
    head = new node;
    head->data = data;
    tail = head;
  }
  else
  {
    temp = head;
    head = new node;
    head->data = data;
    head->next = temp;
  }
  counter ++;
}

template <typename T>
T& Queue<T>::peek()
{
  if (head == nullptr)
  {
    return 0;
  }
  return head->data;

}

template <typename T>
T Queue<T>::pop()
{
  // Empty
  if (head == nullptr)
  {
    return 0;
  }

  // Head = tail
  if (head == tail)
  {
    T data = head->data;
    delete head;
    return data;
  }

  // Size > 1
  curr = head;
  while (curr->next != tail)
  {
    curr = curr->next;
  }
  T data = curr->next->data;
  tail = curr;
  curr = curr->next;
  delete curr;
  counter --;
  return data;
}

template <typename T>
int Queue<T>::size()
{
  return counter;
}

template <typename T>
bool Queue<T>::isEmpty()
{
  if (counter ==0)
  {
    return true;
  }
  return false;
}

template <typename T>
void Queue<T>::clear()
{
  while (head->data != nullptr)
  {
    temp = head->next;
    delete head;
    head = temp;
  }
  if (head == nullptr)
  {
    return;
  }
  delete head;
  return;
}

.ino

. . .
Queue<float> avgQueue;
. . .

error

. . . In function `__static_initialization_and_destruction_0':
. . . undefined reference to `Queue<float>::Queue()'

SOLVED:

Combining the .cpp contents in the .h and removing the .cpp worked.


texts: Mouser/DigiKey part number for female "stacking" headers?

texts:
Adafruit has this wonderful product: http://www.adafruit.com/products/85

What are these actually called? I've looked all over the place in Mouser and DigiKey and can't find them (now, granted, it's impossible to find anything in DigiKey since they discontinued their printed catalog, but I'm digressing...)

They are great for putting other things that are on breakout boards on a tightly-packed breadboard and still be able to attach probes.

Also, sometimes, the board you are trying to attach is this:

As you can see, there is a dip switch blocking the 8-pin header. This is fine for its final resting place (on a board with a socket), but putting it on a breadboard is a bit of a pain. I have quite a few of those, so even though the aforementioned adafruit part is pretty cheap and I could get a bunch, I'd rather know what the real part is called so I can get the sizes I need.

PS: In case you are wondering, and you like old-style nixie tubes, that's http://www.tayloredge.com/storefront/SmartNixie/DataSheets/Datasheet_SmartNixie.pdf.)


texts: I2C_anything from Nick Gammon. Value of two senders to be received and printed by receiverslave

texts:
Following the suggestion of Fiendish to post here:
Hello
Nick, thank you very much for this I2C-anything library that works a treat with two arduinos (one sender, one receiver).
Is there any suggested method or at least an example sketch of having two different sender arduinos send their floats to the receiver  e.g. by alternating slave adresses in the receiver loop? With a simple re-insertion of the section (but with a different address) into the receiver sketch restarting with Wire.begin() and then Wire.begin(new address) things are botched up.
In addition: if I define -float f in sender A- and -float e in sender B- the receiver keeps on printing the float e value in the serial.Print ("float value e"); serial.println(e); -postion, no matter if I swap from Sender A to sender B -by changing the SCL/SDA connections,  and the serial.Print ("float value f");serial.println(f); prints fancy numbers.
If at least the swapping would cause the floats to be printed in the correct position I could maybe switch the respecive senders I2C down in turns....
Of course hotplugging /hotswitching SDA and SCL from senders causes the senders sketch to be blocked at times.
The idea of sending data from Sender B to Sender A, and from Sender A to to receiver left me frustrated the last few hours, due to the fact that Im a total noob and/or that its simply not possible to have two masters send to one slavereciver without running into i2C conflicts. Unless some unknown acrobatics is performed.
The ultimate idea is to have two separate megas (with i2c sensors attached to them) execute feedbackloops and still be able to transfer these values and other values to a display via I2C. the alternate way could be that a dac is used to translate the I2C values into voltages that hardware....)
Any help greatly appreciated
Best
Daniel


texts: Communication between Raspberry PI (Windows IOT) and Arduino with ESP8266

texts:
I'm currently working on a Home Automation project where I have a Raspberry Pi on Windows IoT which communicates with multiple arduinos running on FreeRTOS (I need multi-tasking).
At the moment the communication is through the serial port using Xbees, the Pi sends a command, and the arduino send's back a string in JSON format.

For cost optimisation reasons, I want to try to switch the Xbees with ESP8266 modules. Is it possible to get the same kind of serial communication over WIFI?Thanks.


texts:
I have an Arduino with an Ethernet shield and I want to capture all Ethernet data traffic that connects to the Arduino via [as?] a router. This is because I want to use the Arduino like a honeypot and at the same time resend the Ethernet traffic to the Raspberry, but only specific TCP traffic instead of UDP.

In other words, I want to resend all of the traffic data from an Arduino to a Raspberry Pi, but I need to only resend all of the TCP traffic because the Raspberry reads and parses this. However, I only see examples of UDP traffic but nothing related to TCP. It doesn't matter what kind of port the Arduino listens on, I just need the data out of the other side, can you help me?


texts: Wemos D1 / Witty Cloud D8 doesn't behave as expected

texts:
When using D8 in the code doesn't work, nothing happens, but replacing D8 with 15 works like a charm. And to test this I created the code below. I know that D8 has worked earlier, but I don't remember which version I was using at that time, but it was a yer or more ago.
Environment:

Arduino IDE ver. 1.8.13
ESP8266 board ver. 2.7.4
Witty Cloud or my add on version to WeMos D1 (https://oshpark.com/shared_projects/r3NRvNjx)
WeMos D1 R1 chosen in Board manager

// "Witty Cloud" test program

// A0 - LDR resistor
// D2 - Button
// D6 - Green LED
// D7 - Blue LED
// D8 - Red LED

// Constants won't change. They're used here to set pin numbers:
const int LDR = A0;
const int BUTTON = D4;
const int GREEN = D6;
const int BLUE = D7;
const int RED = D8;

void setup()
{
  Serial.begin(115200);
  pinMode(LDR, INPUT);
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  pinMode(BUTTON, INPUT);
}

void loop()
{

  delay(1000);

  Serial.println("");

  Serial.print("LDR: ");
  Serial.println(analogRead(LDR));

  digitalWrite(RED, HIGH);
  digitalWrite(BLUE, LOW);
  Serial.println("--- Red ---");

  delay(1000);
  digitalWrite(RED, LOW);
  digitalWrite(GREEN, HIGH);
  Serial.println("--- Green ---");

  delay(1000);
  digitalWrite(GREEN, LOW);
  digitalWrite(BLUE, HIGH);
  Serial.println("--- Blue ---");
}


texts: Enable free fall detection using Arduino

texts:
I'm trying to get an arduino board to detect simple free fall condtions. Currently, I have a 9DOF sensor (https://learn.sparkfun.com/tutorials/lsm9ds0-hookup-guide) and am able to get the raw data from the sensor.

However I am unsure what to do from here onwards. From what I manage to gather, there is an alternative sensor ADXL345 accelerometer that has an inbuilt free fall component. I have tried modfying the code in such a way that it will work with the sensor I am using but to no avail.

The free fall detection does not need to be extremely accurate/precise considering there are many fall/jerk patterns. It is just for a proof of concept for a project of mine. With that in mind, any suggestions on how to proceed will be greatly appreciated (or if I should just get the ADXL345 accelerometer).

Thank you.


texts:
Is there a way to make a listener for a key press to begin a loop?

Example:  I press the Tab key on my keyboard and the programmed loop begins running.

Essentially creating a keyboard hotkey.


texts: Problems burning bootloader on custom ATMEGA2560 board for High-powered model rocketry

texts:
I've designed a custom board meant for high-powered model rocket telemetry & duel-deployment.  (More info upon request)

To do this, I've soldered a ATMEGA2560 (yes, overkill, but I needed multiple hardware serials), with the plan on using the ICSP programming header I designed on the board to burn the Arduino bootloader, and then use the super-easy ftdi-compatible serial connector to program the board....

Problem is, I have thus far been completely unable to burn the bootloader.  I've double-checked the wiring ten times, checked the labeling on my board, checked my board's schematic twice, and re-checked the chip's datasheet to make sure I didn't screw up the pinout, even held a jumper past my fancy reset circuitry that I largely copied from the official Uno schematic.

I've largely been using Nick Gammon's excellent "bootloader programmer" sketch Link on a Clone Arduino Mega.  But I've tested the connections and sketch by using it to program the bootloader on a Arduino Pro Mini successfully with no hitch at all.  :(

Attempting to enter ICSP programming mode..........................................
Failed to enter programming mode. Double-check wiring!

Here's a Board and (Schematic I can't post because I'[m new to the Arduino side of stack overflow...  so replace the URL with schematic.png) of my board, and I'll upload a picture of my soldered board soon, but I'm actually quite confident of my soldering job...

Really just completely out of ideas, and very demoralized because the project I've been working on for months isn't working, and I have nothing specific to even point at...


texts: Piezo sensor requires parallel or pull-down resistor?

texts:
Apologies but I didn't happen to find ultimate answer to this.
I'm trying to make a simple piezo sensor (https://www.sparkfun.com/products/10293) which triggers something (e.g. a sound or lights up a LED) when it's pressed. This is similar to Arduino "Knock Lock" project.
However, I see there are 2 different basic ways to connect the piezo as vibration sensor:
Way 1) [as in Arduino project]

Piezo + to 5V
Piezo - to A0
1MΩ Resistor between A0 and GND

Way 2) [as in many other references on the internet]

Piezo + to A0
Piezo - to GND
1MΩ Resistor between A0 and GND

I tried both and have very different behaviours.
Way 1 seems working correctly: analogRead(A0) returns a value related to how strong the vibration is, and then decays to almost 0 (I expected 0 but it stays to 50-60ish).
Way 2 provide more of an impulse-type response, and stays at 400ish after triggered.
Are these behaviors correct and what's the proper way for piezo sensor?
Using Arduino UNO powered via USB.


texts:
I'd like to use an H-Bridge  AND send PWM signal.
I've used this schematics: http://itp.nyu.edu/physcomp/Labs/DCMotorControl
and use the PWM signal inside the enablePin. But the H_Bridge is getting very hot.
Am I wrong?
EDIT:
I'm using and H-Bridge but not for driving a motor, instead I'm driving a peltier cell (like this one: https://www.sparkfun.com/products/10080). What I'm trying to achieve is to have a fixed peltier cell and to have in the same side sometimes hot, sometimes cold. This behaviour is done by switching the positive and negative with the H-Bridge. To control how much cold and how much hot I'm using PWM.


texts: Why calling digitaWrite(pinNum,HIGH) before setup() not working?

texts:
I am writing a library to operate a linear actuator, let's call the library ActuatorV2. It is composed of two files, a .h and and .cpp files. To create an object, I instantiate the object as follows

Actuator act(pulsePin,directionPin,enablePin);

Within the constructor of the object, four tasks are performed:

1) pin assignment,

2) setting pin modes,

3) setting pulse frequency

4) enabling the actuator.

When performing the fourth task (enabling), I simply set the enablePin to HIGH as follows digitalWrite(enablePin,HIGH); There is absolutely nothing special here, but for some odd reason, when setup() is called in the sketch, the enablePin is set back to LOW. I know this because I have an LED light connected to the enablePin, and I visually monitor it during the operation.

Any idea why this happens?

I am aware that in the documentation of setup() here, it is clearly stated that pinMode() should be placed in setup(). But I have used the approach shown in the MWE before a few months ago, and it was working just fine.

Hardware used

MacBook Pro

Arduino Due

MWE

Sketch

#include <ActuatorV2.h>

// defining actuator pins and properties
const int pulstPin      = 4;
const int directionPin  = 5;
const int enablePin     = 6;
const int pulseFrequency= 500;

// initializing the actuator
Actuator act(pulstPin, directionPin, enablePin, pulseFrequency);

void setup() {
    // do nothing
}

void loop() {
    // do nothing
}

Library (Actuator.h, Actuator.cpp)

Actuator.h

#ifndef Actuator_h
#define Actuator_h

#include<Arduino.h>

class Actuator{
    private:
    // private variables
    // pins
    int _pulsePin;
    int _directionPin;
    int _enablePin;
    // pulse frequency parameters
    int _pulseFrequency;
    int _pulseDelay = 5;   // 2.5 microseconds manufacturer recommendation
    int _interpulseDelay;

    // private methods
    void assignPins(int pulsePin, int directionPin, int enablePin);
    void setPinModes();

    public:
    // constructors
    Actuator(int pulsePin, int directionPin, int enablePin, int pulseFrequency);
    // public methods
    void setPulseFrequencyParameters(int freq);
    void enable();
};

#endif

Actuator.cpp

# include<ActuatorV2.h>
# include<Arduino.h>

Actuator::Actuator(int pulsePin, int directionPin, int enablePin, int pulseFrequency){
    // 1) pin assignment
    assignPins(pulsePin,directionPin,enablePin);

    // 2) setting pin modes
    setPinModes();

    // 3) setting pulse frequency
    setPulseFrequencyParameters(pulseFrequency);

    // 4) enable actuator
    enable();
}

void Actuator::assignPins(int pulsePin, int directionPin, int enablePin){
    _pulsePin = pulsePin;
    _directionPin = directionPin;
    _enablePin = enablePin;
}

void Actuator::setPinModes(){
    pinMode(_pulsePin,OUTPUT);
    pinMode(_directionPin,OUTPUT);
    pinMode(_enablePin,OUTPUT);
}

void Actuator::setPulseFrequencyParameters(int pulseFrequency){
  int _pulseFrequency = pulseFrequency;
  int minPeriod = 10; // 10 micro-seconds which is 4 X 2.5 (manufacurer recommended pulse width for reliable operation)
  /*
  ---------------------------------------------------------------------
  Pulse shape

  3.3 V
        |  |``````````|                     |``````````|
        |  |          |                     |          |
        |__|          |_____________________|          |__________ time
  0   V
           \__________/\____________________/
                pd              ipd
           \________________________________/
                     one pulse

  pd: pulse delay. Minimum 3 micro seconds
  ipd: inter-pulse delay. Minimum 3 micro seconds
  ---------------------------------------------------------------------
  */

  float period = 1.0/((float) pulseFrequency);

  if (period < minPeriod){
    _pulseDelay = 5;
    _interpulseDelay = 5;
  } else  {
    _pulseDelay = 5;
    _interpulseDelay = period - _pulseDelay;
  }
}

void Actuator::enable(){
  digitalWrite(_enablePin,HIGH);
  delay(500); // delay to observe the result if effective.
}


texts:
I am trying to convert a float value to a 4-byte hexadecimal value.

For example my input is: 58.5. My expected output is: 426A0000 or like 0x42 0x6A 0x00 0x00.

My program is:

void setup() {
  Serial.begin(9600);
  float z = 128;
  unsigned i;
  unsigned char *chpt;
  chpt = (unsigned char *)&z;
  Serial.print("Float Value             : ");
  Serial.println(z);
  Serial.print("4 Byte hexadecimal Value: ");
  for (i = 0; i < sizeof(z); i++) {
    Serial.print(chpt[i],HEX);
    //Serial.print(" ");
  }
  Serial.println();
}
void loop() {
}

My current output is:

Float Value             : 128.00

4 Byte hexadecimal Value: 00043


texts: Reusing Digispark ATtiny85 micro-USB as 1-wire bus

texts:
I'm working on a project of my home plants irrigation/hydroponic system(not cannabis!)) just chilies and other eatables). Also I'm trying to recycle modules, wires and other projects' leftovers such as Digispark ATtiny modules. I'd to use it as a slave controller to pass some sensors' data to master-controller. (Sensors are soil pH, moisture sensor, water counter, PIR as a cat detector).
Now I'm looking for a way to reuse Digispark USB-connector(3 and 4 pins) as a communication bus. Those pins have pull-up resistors and diodes attached to, so that's why it could be difficult.
My goal is to reduce extra components count, reuse old micro-usb wires, connect digispark slave controller using existing USB connector. And optionally save the ability to program digispark via the same connector.
I'd like to use 1-wire/i2c protocols for communication, cause it would be better to connect multiple slave-devices on the same bus.
So here are a few troubles:

choose of the protocol. I2C sounds better, but the popular library TinyWireS use USI pins to communicate which are different to USB pins.
1-wire looks suitable, and it also have pullup resistors on the bus.
voltage shift on these pins
How do you think Is it possible to connect multiple 1-wire slave digispark devices on the same bus. Do I need an optocoupler or logic level convertors?


texts: I'm interested in making a remote camera that could take and process still photos and send over cellular data using the Arduino MKR GSM. Is this feasible with the specs of the arduino? If it is does anyone have any suggestions of camera modules?


texts: Arduino nano & pro micro SPI simple communication

texts:
I'm working with Arduino boards with AVR C coding to perform simple SPI communication from master for simple blink application on slave side.

They don't work, the TX function on the master side doesn't seem to work, after serial monitor debugging is discovered the function never get over the while loop! Why is that?

Here are the codes I worked on last night:

Master:

/* nano board is the Master and transmit
  data to slave to blink LEDs */

void SPI_Init(void);
void SPI_TX(uint8_t data);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);//start Serial
  Serial.println("Setting Up");
  void SPI_Init();
  delay(100);
  Serial.println("SPI intialization is complete");
}

void loop() {
  uint8_t d = 0x20;
  SPI_TX(d);
  Serial.println("just sent the 1st byte");
  _delay_ms(400);
  d = 01;
  SPI_TX(d);
  Serial.println("just sent the 2nd byte");
  _delay_ms(400);
}

void SPI_Init(void)
{
  DDRB = (1 << DDB3) | (1 << DDB1); // DDB2 MOSI, DDB1 SCK
  SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR0);
}

void SPI_TX(uint8_t data)
{
  SPDR = data;
  while (!(SPSR & (1 << SPIF)));
}

-------------------------------------------------------------- -

Slave:

-------------------------------------------------------------- -

/* pro micro as slave and receives data then push them on
  PORTD and PORTB to blink LEDs */

void SPI_Init_S(void);
void SPI_RX(void);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);//start Serial
  Serial.println("Setting Up");
  SPI_Init_S();
  delay(100);
  Serial.println("SPI intialization is complete");
  DDRD = (1 << DDD5); // TX LED as output
  DDRB = (1 << DDB0); // RX LED as output
}

void loop() {
  // put your main code here, to run repeatedly:
  SPI_RX();
  PORTD = SPDR;   // blink the TX LED on pro micro board
  _delay_ms(500);
  SPI_RX();
  PORTB = SPDR;   // blink the RX LED on pro micro board
  _delay_ms(500);
}

void SPI_Init_S(void)
{
  SPCR = (1 << SPE) | (1 << SPR0);
}

void SPI_RX(void)
{
  return SPDR;
}


texts: Maximum delay time for a switch read loop

texts:
I have this simple program:

void loop() {
  sendInputs();
  delay(10);
}

the sendInput() method reads some digital inputs connected to an external switch and sends a command via serial port.

My question is: what is the maximum delay time to correctly read an external switch? Consider that this switch is pressed by a human like a mouse click.


texts:
I have connected some sensors to an Arduino Uno (but the final code should run on a Pro-Mini) with an ENC28J60 shield. The sensor code works fine - until I add EtherCard. I tried UIPEthernet first, but it's even worse. The problem is the memory footprint. The ethernet libraries are consuming so much memory that random malfunctions do occur.
So I was thinking about removing TCP from the EtherCard library, because I don't need it anyway. I only need IP, ARP, UDP, and based on that DHCP, DNS and NTP.
Has someone already done this?
Is there a stripped-down library?
The file tcp.cpp is pretty big (the biggest in this lib). Is it safe to remove all methods with "tcp" in their name?
Or is there a better solution for this situation?


texts:
I am currently making a GPS tracker with UNO and SIM808 (this is the model.

It says The range of voltage of Lithium battery input power is 3.5 - 4.2V. for the module. I am aware that UNO needs 5V to power.

I want to make it compact as possible so it can be placed within the dashboard of a car or motorcycle.

How do I power both of this using just one battery holder?


texts: How to remove Adafruit Pro Trinket bootloader flashing startup sequence

texts:
From what I understand, the Pro Trinket has "Optiboot" which allows it to detect which boot loader you are trying to use, one for USB and one for FTDI. When it's in this "bootloader state" the red LED on pin 13 buses for 10 seconds before it starts to run the program I've programmed.

Can I remove this Optiboot functionality? Would that entail permanently choosing a single boot loader/interface?

One problem I have with this is that along with the LED on 13, it causes the LED strip I have attached to pins 9, 10, 11 to blink. I would also really like to not have to wait 10 seconds to start running code.

Here's the page on Adafruit's site that talks about the bootloader[s] on the Pro Trinket.

Thanks!


texts: RTClib library dependency on Wire library

texts:
I downloaded the RTClib library from https://github.com/adafruit/RTClib.  In every provided example, #include <Wire.h> is written immediately above #include "RTClib.h" at the top of the sketch.

Why is this necessary?  I know the RTClib library requires the functionality of the Wire library but, if this is the case, why can't I just #include <Wire.h> at the top of RTClib.h?  I have tried the latter, even using just the following sketch, but my sketch failed to compile.

RTClib.h:

// Code by JeeLabs http://news.jeelabs.org/code/
// Released to the public domain! Enjoy!

#ifndef _RTCLIB_H_
#define _RTCLIB_H_

#include <Wire.h>
...

#endif // _RTCLIB_H_

Sketch:

#include "RTClib.h"
void setup() {}
void loop() {}


texts: Rc car which returns to middle when left or right button is not pressed

texts:
Hi i am currently working on a school project , my only problem is that i want my RC car to return to middle direction (which i have set to 66 in the servo motor) when the left or right button is not pressed . i used if statements but it doesn't work. Are there any function that i can use ?
Here is my code for the transmitter i used the RC-Switch Library (https://www.arduinolibraries.info/libraries/rc-switch)

#include <RCSwitch.h>
#include <Servo.h>

const int IN1 = 3;
const int IN2 = 4;
const int trigPin = 5;
const int echoPin = 6;
const int Buzzer = 8;
int distance = 0;
int value = 0;
long duration;
RCSwitch mySwitch = RCSwitch();
Servo myservo;

void setup () {
  mySwitch.enableReceive(0);
  myservo.attach(7);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  pinMode(Buzzer,OUTPUT);
  Serial.begin (9600);    // Debugging only
  Serial.println ("Receiver Ready");
}

void loop () {

  delayMicroseconds(10);
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance= duration*0.034/2;
  // Prints the distance on the Serial Monitor
  //Serial.print("Distance: ");
  //Serial.println(distance); //distance is the returned integer,

 if (mySwitch.available()) {

    value = mySwitch.getReceivedValue();
    Serial.println (value);

      if(value == 1) {
        forward ();
        Serial.println (" = forward");
      }

      if(value == 2){
        backward ();
        Serial.println (" = backward");
      }

      if(value == 3) {
        left ();
        Serial.println (" = left");
      }

      if(value == 4) {
        right ();
        Serial.println (" = right");
      }
      Serial.print(" ");
    }
  mySwitch.resetAvailable();
  //myservo.write(45);
}

void forward () {
  digitalWrite (IN1, LOW);
  digitalWrite (IN2, HIGH);
}

//value = mySwitch.getReceivedValue();
void backward () {

  if ((distance < 50)&& (value == '2'))
  {
    digitalWrite (IN1, LOW);
    digitalWrite (IN2, LOW);
    digitalWrite (Buzzer, HIGH);
  }
  else if ((distance > 50)&& (value == '2'))
  {
    digitalWrite (IN1, HIGH);
    digitalWrite (IN2, LOW);
    digitalWrite (Buzzer, LOW);
  }
}
// 66 is middle

void right () {
  if (value == 4){
    myservo.write(110);
  } else
  myservo.write(66);
}

void left () {
  if (value == 3){
    myservo.write(50);
  }else
 myservo.write(66);
}

And Here is The transmitter code

// TRANSMITTER CODE

#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();
// Assigning controller buttons to Digital Pins
 int forward = 11;
 int reverse = 10;
 int rightTurn = 9;
 int leftTurn = 8;

void setup () {
  pinMode (forward, INPUT_PULLUP);
  pinMode (reverse, INPUT_PULLUP);
  pinMode (rightTurn, INPUT_PULLUP);
  pinMode (leftTurn, INPUT_PULLUP);
  mySwitch.enableTransmit(7);
  Serial.begin (9600);         // Debugging only
  Serial.println ("Transmitting");
}

void loop () {
  if (digitalRead(forward) == LOW) {
    mySwitch.send(1, 24);
    Serial.println ("Forward");
  }

  if (digitalRead(reverse) == LOW) {
    mySwitch.send(2, 24);
    Serial.println ("Reverse");
  }

  if (digitalRead(leftTurn) == LOW) {
    mySwitch.send(3, 24);
    Serial.println ("Left Turn");
  }

  if (digitalRead(rightTurn) == LOW) {
    mySwitch.send(4, 24);
    Serial.println ("Right Turn");
  }
}


texts:
I am writing a project that involves using complementary filters to combine gyroscope and accelerator readings in 3 directions. The relevant code is below.

class CompFilter {
 public:
   long prevTime;
   float alpha;
   int angle;

   CompFilter(float Alph);
   int combine (float gyroRate, float accelAngle);
};

CompFilter::CompFilter(float Alph) {
 alpha = Alph;
 prevTime = 0;
 angle = 0;
}

int CompFilter::combine(float gyroRate, float accelAngle){
  Serial.println("Here THREE");

 long timeStep = millis() - prevTime;
 if (timeStep == 0) { timeStep = 1;}

 angle = alpha * (angle + gyroRate * timeStep);

 angle += (1.0 - alpha) * accelAngle;

 prevTime = millis();

 return angle;
}

//Global Objects
CompFilter *senPitch; CompFilter *senRoll;  //Declare Complementary Filters

//Adjustable Parameters
float alpha = .5;   //Constant affecting Gyro's vs. Accel's influence on sensor reading

void setup(void)
{
  //Open Data Channel
  Serial.begin(115200);
  Serial.println(F("IMU Complementary Filter Tester")); Serial.println("");

 //Initialise TMU sensors
 sensorInit(accel, mag, gyro);
 senPitch = new CompFilter(alpha); senPitch = new CompFilter(alpha);
  Serial.println("HERE ONE");
}

void loop(void)
{
 //Variables for reading sensors
 sensors_event_t accel_event, mag_event, gyro_event;
 sensors_vec_t   orientation;

 // Retrieve Sensor Readings
 accel.getEvent(&accel_event);
 gyro.getEvent(&gyro_event);
 mag.getEvent(&mag_event);

 Serial.println("HERE TWO");

 int anglePitch = senPitch->combine(gyro_event.gyro.y, orientation.pitch);
 int angleRoll = senRoll->combine(gyro_event.gyro.x, orientation.roll);

}

I had to keep track of a couple of pieces of information for each direction, so rather than trying to use parallel arrays, I created a CompFilter class. I think I am using the correct syntax in the class and constructing the object, but I am getting very unusual outputs from Serial.print().

RE ONE
RE TWO
Here THREE
Here THREE
entary Filter Tester

Depending on how I fiddle with the code, I can get setup() repeating over and over or loop() running once before silently failing.

I suspect that I have misdirected a pointer somewhere, but I am not sure. I would appreciate any help.


texts: How to write a sketch when adding more devices to an I2C data line?

texts:
I am building a weather station, using a battery-operated outside unit, that transmits data from a DHT22 sensor to a unit inside my house.

The inside unit is using I2C communications from my Arduino Uno to my LCD display.

I would like to add a BMP180 sensor which also uses I2C communications.

My question is, how would you write a sketch to incorporate both the BMP180 sensor and the LCD display on to one I2C line?


texts: How do I upload an Arduino STM32 binary from the Mac command line?

texts:
I've compiled an Arduino program via a Makefile and have the resulting hex file.

From the Mac command line, how do I upload this hex file to my STM32 Cortex M3 board?  For an ATMEL processor I would use avrdude.


texts:
I recently upgraded my windows10 from version 1803 to 1903. I had to do a clean install to accomplish it though, but my question is, I downloaded Adriano IDE 1.8.9 and installed it but it won't launch. It starts, then the window closes and that's it. Does anybody have any thoughts on what's going on? Or better yet what's not going on?

Thanks, Dennis


texts:
Help me out here. I don't know what I'm missing.
I have this code in my arduino IDE
#include "Foo2.h"
void setup() {
  // put your setup code here, to run once:

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

And I have five files: Foo.h, Foo.cpp, Foo2.h, Foo3.cpp and Foo.h
Foo.h
#ifndef Foo_H
#define Foo_H

class Foo
{
    public:
    Foo();

    public:
    bool Fooa();
    bool Foob();
};
#endif

Foo.cpp
#include "Foo.h"

Foo::Foo()
{

}

bool Foo::Foob()
{
    return true;
}

Foo2.h
#ifndef Foo2_H
#define Foo2_H
#define LIBRARY_VERSION 1.0.0
#include "Foo.h"

bool Foo::Fooa()
{
    return true;
}
#endif

Foo3.h
#ifndef Foo3_H
#define Foo3_H
#include "Foo2.h"

class Foo3
{
    public:
        Foo3();
        Foo _foo;
};
#endif

Foo3.cpp
#include "Foo3.h"

Foo3::Foo3()
{
}

And it is give me an error:
libraries\Foo\Foo3.cpp.o (symbol from plugin): In function `Foo::Fooa()':
(.text+0x0): multiple definition of `Foo::Fooa()'
sketch\kk2.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
exit status 1

what i'm doing wrong
regards,


texts:
I modified a code which replies BAR when I send FOO. The problem is the if else statement always lands on else which prints Wrong command. I tried comparing it to string FOO(??) and also comparing it to char FOO with the same buffer size but no joy. This is the code:

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>

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

WiFiUDP Udp;
unsigned int localUdpPort = 9999;  // local port to listen on
char incomingPacket[255];  // buffer for incoming packets
char command_1[255] = "FOO"; //Tried same buffer size... no luck
char replay_1[] = "BAR";
char wrong[] = "Wrong command";

void setup()
{
  Serial.begin(74880);
  Serial.println();
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
  Udp.begin(localUdpPort);
}

void loop()
{
  int packetSize = Udp.parsePacket();
  if (packetSize)
  {
    int len = Udp.read(incomingPacket, 255);
    if (len > 0)
    {
      incomingPacket[len] = 0;
    }
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.write(incomingPacket); // Prints the same as from icoming packet which is FOO (Debbuging)
    if (incomingPacket == command_1) { //Tried comparing to same buffer size "FOO" and string "FOO"... no luck
      Udp.write(replay_1);
    }
    else {
      Udp.write(wrong);
    }
    Udp.endPacket();
  }
}


texts:
My display is not responding to this code. Help please

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_MOSI 10
#define OLED_CLK 9
#define OLED_DC 12
#define OLED_CS 13
#define OLED_RESET 11
Adafruit_SSD1306 display(OLED_MOSI,OLED_CLK,OLED_DC,OLED_CS,OLED_RESET);

void setup(){
  Serial.begin(9600);
  display.begin(SSD1306_SWITCHCAPVCC);
  display.clearDisplay();

  display.setTextSize(1);
  display.setCursor(30,30);
  display.print("Hello WOrld");
  display.display();
  }

  void loop(){

    }


texts: BASCOM-AVR stk500_2_ReceiveMessage(): timeout: -1

texts:
Arduino Uno R3

Windows 10

Bascom AVR

The ON is alright.

The LED flickers now and then.

The RX and TX flickers when I press the program button on Bascom but then disappears almost immediately.

Hello. I have been having this trouble since yesterday. It always appears whenever I click the program button on Bascom. I feel so stupid having to Restart my PC and checking the Device Manager again and again. I am still new to this.
The COM Port is correct and everything else matches. I do not know how to solve this. Please help, I have already watched tutorials but they all assume you have great background in programming which I don't.

So I hope you can use easy terms.
Thank you.


texts: Switching a Solenoid Using Arduino's 5V Output?

texts:
I'm a bit stumped on how to switch on a solenoid using a transistor using my Arduino Nano's 5v Output. The solenoid runs on 12V, so I used an NPN transistor to connect the 12V source to the solenoid whenever Arduino sends current to the transistor's base. I connected all the grounds together to the Nano's ground pin, but the solenoid still doesn't switch.
I know the transistor works properly, because the solenoid switches when I use the battery to send base current instead of the Nano. I would think the Nano is capable of sending enough current to activate the Collector -> Emitter path but might be wrong. I'm also wondering if it's an issue with grounding the circuit, but I've made sure there is a common ground. What do you think I'm doing wrong? BTW the transistor I am using is D882P. I would appreciate any help.

simulate this circuit – Schematic created using CircuitLab


texts: How to do run time calibration for MPU9250?

texts: Does anyone know how to do the run time calibration for MPU9250 ?


texts: Good voltage and resistor value for string of LEDs

texts:
I building multiple parallel strings of 4 LEDs in series.

Since the four LEDs in series have a combined forward voltage of 12.56V at 20mA, and it's powered by 2 AA batteries, I have added a voltage booster.

Now my question is, since I can both choose the output voltage of the boost converter, and the resistor added to each string of 4 LEDs, what would be a reasonable value for both?

I could set the voltage to exactly 12.56V and not use a resistor, but that would probably lead to uneven current spread between the sets of 4 LEDs, as their forward voltage can differ slightly due to manufacturing differences.

On the other hand, I don't want to set the voltage too high, and wast a lot of power.

So what would be an acceptable voltage drop over a current limiting resistor?


texts: Feeding microcontroller and linear actuators (motors) with the same power supply

texts:
I have already made a diagram using a motor controller. I want to use only one power supply to feed arduino and motors. I want to use MDD10 dual motor driver.

The details of the actuators each one is:

Input voltage: 12VDC,
Max Load: 750N(168.607lbs),
Stroke Length: 16 inch,
Travel Speed: 12mm/s,
Duty Cyle: 25%,
Current: 5A.

The power supply is 12V, 10A.

Could you please check if it is ok, or which would be the best solution?

Some of my concerns are:

Be sure if the feed of 12 volts for the motors, and 5 volts for Arduino are correct and can live together as shown.

Be sure if the wiring for the Arduino, driver and motors is correct since it looks kind of simple.

I want to know if this is the natural approach by doing it with a voltage regulator to feed the Arduino and with 12V 10A power supply to feed the motors, or if there are other, better options to make the circuit feed only using one power supply (12V, 10A).

MDD10 Datasheet Link: https://www.robotshop.com/media/files/content/c/cyt/pdf/cytron-10a-7-30v-dual-channel-dc-motor-driver-shield-datasheet.pdf

Thanks in advance

UPDATE

I have increased power supply to 13A, also changed the linear voltage regulator (7805) to a switching voltage regulator (OKI-78SR-5), what do you think about this approach?

Or I should try with the 12V DC Vin of Arduino(I understand that it works with a linear voltage regulator)? Being this option, it could be maybe with a voltage pre-regulation stage(for example from 12V to 9V) or maybe connecting directly to the jack.

Thanks, Best Regards.


texts: Arduino WebSocket Client "Connection Failed"

texts:
I use this code to connect Arduino MKR1000 to API through Web Socket, but it didn't connect to the server.
Can any one help me to correct the code.

This is the Arduino code:

#include "Arduino.h"
#include <WiFi101.h>
#include <SPI.h>
#include <WebSocketClient.h>

char server[] = "192.168.2.128";
IPAddress server1(192, 168, 2, 128);
WebSocketClient webSocketClient;
WiFiClient client;

char path1[] = "/api/WebSocketTest";
int port1 = 8060;
char ssid[] = "**************";
char pass[] = "**************";

void setup() {
  pinMode(LDR, INPUT);
  pinMode(LED, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(SWITCH, INPUT);
  Serial.begin(115200);
  delay(10);
  while (!Serial) {
  }

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, pass);

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

  Serial.println("");
  Serial.println("WiFi connected");
  printWifiStatus();
  delay(3000);
  Serial.println("setup done");
  delay(1000);

  //  webSocketClient.setDebug(&debug);
  webSocketClient.connect(server, port1, path1);
  if (webSocketClient.connected() == true) {
    Serial.println("Connected");
  }
  else {
    Serial.println("Not Connected");
  }
  webSocketClient.onMessage(onMessage);
  webSocketClient.onOpen(onOpen);
  webSocketClient.onError(onError);
}

void loop() {
  webSocketClient.monitor();
}

void onOpen(WebSocketClient webSocketClient) {
  Serial.println("EXAMPLE: onOpen()");
}

void onMessage(WebSocketClient webSocketClient, char* message) {
  Serial.print("Received: ");
  Serial.println(message);
}

void onError(WebSocketClient webSocketClient, char* message) {
  Serial.print("ERROR: ");
  Serial.println(message);
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

And this is a part from the library used "WebSocketClient.h":

void WebSocketClient::connect(char hostname[], int port, char protocol[], char path[]) {
  _hostname = hostname;
  _port = port;
  _protocol = protocol;
  _path = path;
  _retryTimeout = millis();
  _canConnect = true;
}

Edit 1: The output:

Connecting to WiFi-Repeater1

WiFi connected
SSID: WiFi-Repeater1
IP Address: 192.168.2.147
signal strength (RSSI):-68 dBm
setup done
Not Connected
ERROR: Connection Failed!
ERROR: Connection Failed!
ERROR: Connection Failed!
ERROR: Connection Failed!
ERROR: Connection Failed!
ERROR: Connection Failed!


texts: I’m reassembling an LED strip, SK6812, that I had cut into smaller lengths. I don’t have a lot of faith in the connectors I’m using or my ability to solder, so I’d like to test it before I put power to it. A simple continuity test is easy for the power “wires” but how do I test the signal “wire”?


texts: Does a moisture sensor need warm-up time?

texts:
I am trying to use a moisture sensor to identify the moisture value of my plants. (As every one does.)

The sensor was connected to VCC all the time and my battery goes empty after a short time. So I decided to connect power only at the time I read from the sensor (on the arduino with digitalWrite(moisture_vcc, HIGH).

To problem is that the values were too high.

So I'm wondering if these kind of sensors need a "warm-up time"? And If so, how long is it?

Any experience with it?


texts: Powering Arduino through 12V USB communication unstable

texts:
When powering Arduino through Japan Jack at 12V USB communication becomes unstable and frequently interrupts/disconnects. Using Arduino Uno R3 and Linux on the connected computer.

Does anyone have any insight why this might be happening?


texts:
I want to read the source code of an arduino library that comes with the IDE.
Specifically the GSM.h

I dont know the location of the standard libraries that come with the IDE.

I only know the location of the user installed libraries.

So where is the source code of GSM.h?


texts: elechouse Voice recognition v3 module not responding when i send command using Access port serial tool

texts: I have this challenge of receiving data when I send a command to voice recognition v3 module. the uart connections are okay, but when I send a command I don't receive a response on the terminal. the prolific usb-ttl with drivers installed blinks when I send a command but still I get no response. please help in debugging.


texts: scroll text through multiple i2c connected dot matrix displays

texts:
I have 4 dot matrix displays, every one of them connected to an i2c and accessible with 0x70, 0x71, 0x72 and 0x73. All these work just fine when I address them apart. What I want to achieve is a scrolling text throughout all 4 displays. How can I do this? Are there any libraries around that already do this? (I did not find any).

Basically, this is my code:

#include <Wire.h>
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"

Adafruit_8x8matrix matrix[4];

void setup() {
  Serial.begin(9600);
  Serial.println("4x(8x8) LED Matrix Test");
  matrix[0].begin(0x70);
  matrix[1].begin(0x71);
  matrix[2].begin(0x72);
  matrix[3].begin(0x73);
}


texts: Arduino MKR1000 problem with only two HTTP Client Post Request

texts:
When I use MKR1000 with ARDUINOHTTPCLIENT library and some simple http post example I have problem that my Arduino sends the request only twice. After that I get error code in response -2. I have tried to change time and restart the Arduino many times, but I keep getting the same problem. I change server domain where my Arduino make call and the problem is still same.

Here is code. Can anyone help me:

#include "ArduinoHttpClient.h"
#include "WiFi101.h"

//Setup Wifi Parameters
char ssid[] = "xxxxxxxxxxxx";
char pass[] = "xxxxxxxxxxxx";
char serverAddress[] = "xxxxxx.xxxxxxx.com";
int port = 80;

WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
String response;
int statusCode = 0;

void setup()
{
  Serial.begin(9600);
  while ( status != WL_CONNECTED)
  {
    Serial.print("Attempting to connect to Network named: ");
    Serial.println(ssid);

    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);
    delay(6000);
  }

  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
}

void loop()
{
  Serial.println("making POST request");
  String contentType = "application/x-www-form-urlencoded";
  String postData = "name=Alice&age=12";

  client.post("/public/insert_mysql.php HTTP/1.1", contentType, postData);

  // read the status code and body of the response
  statusCode = client.responseStatusCode();
  response = client.responseBody();

  Serial.print("Status code: ");
  Serial.println(statusCode);
  Serial.print("Response: ");
  Serial.println(response);

  Serial.println("Wait five seconds");
  delay(5000);
}

This is information from Serial Debug:

SSID: xxxxxxxxxxxxx
IP Address: xxxxxxxxx
making POST request
Status code: 200
Response:
Wait five seconds
making POST request
Status code: 200
Response:
Wait five seconds
making POST request
Status code: -2
Response:
Wait five seconds
making POST request
Status code: -2
Response:
Wait five seconds
making POST request
Status code: -2
Response:
Wait five seconds
making POST request


texts:
Got a Duratech motor shield today, and I'm wondering why my motors do not run. Appreciate any help. The code I am using is the Adafruit sample code, Motorparty. The servos work however the motors do not.
Here is a photo of my setup, code is below:

/*
This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM
control

For use with the Adafruit Motor Shield v2
---->   http://www.adafruit.com/products/1438

This sketch creates a fun motor party on your desk *whiirrr*
Connect a unipolar/bipolar stepper to M3/M4
Connect a DC motor to M1
Connect a hobby servo to SERVO1
*/

#include <Wire.h>
#include <Servo.h>
#include <Adafruit_MotorShield.h>

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Connect a stepper motor with 200 steps per revolution (1.8 degree)
// to motor port #2 (M3 and M4)
Adafruit_StepperMotor *myStepper = AFMS.getStepper(200, 2);
// And connect a DC motor to port M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(3);

// We'll also test out the built in Arduino Servo library
Servo servo1;

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("MMMMotor party!");

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  // Attach a servo to pin #10
  servo1.attach(10);

  // turn on motor M1
  myMotor->setSpeed(200);
  myMotor->run(RELEASE);

  // setup the stepper
  myStepper->setSpeed(10);  // 10 rpm
}

int i;
void loop() {
  myMotor->run(FORWARD);
  for (i=0; i<255; i++) {
    servo1.write(map(i, 0, 255, 0, 180));
    myMotor->setSpeed(i);
    myStepper->step(1, FORWARD, INTERLEAVE);
    delay(3);
 }

 for (i=255; i!=0; i--) {
    servo1.write(map(i, 0, 255, 0, 180));
    myMotor->setSpeed(i);
    myStepper->step(1, BACKWARD, INTERLEAVE);
    delay(3);
 }

  myMotor->run(BACKWARD);
  for (i=0; i<255; i++) {
    servo1.write(map(i, 0, 255, 0, 180));
    myMotor->setSpeed(i);
    myStepper->step(1, FORWARD, DOUBLE);
    delay(3);
 }

  for (i=255; i!=0; i--) {
    servo1.write(map(i, 0, 255, 0, 180));
    myMotor->setSpeed(i);
    myStepper->step(1, BACKWARD, DOUBLE);
    delay(3);
 }
}


texts:
I am using SHT21 temp sensor with ESP32 using I2C. The sensor only reports temp of -273 and 0 for RH. The sensor is not faulty as I have tried this on an Arduino UNO with the same sketch and it works fine. I am using the default data and clk pins on ESP 32. Also I tried it on a different ESP32 board as well as powering the sensor from the ESP32 and externally but still get incorrect readings. I suspect it is more of a software issue than a hardware one. Could you please help me find the cause?
Here is my sketch:
#include <Wire.h>
#include <Sodaq_SHT2x.h>

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

void loop()
{
  Serial.print("Humidity(%RH): ");
  Serial.print(SHT2x.GetHumidity());
  Serial.print("     Temperature(C): ");
  Serial.println(SHT2x.GetTemperature());
  Serial.print("     Dewpoint(C): ");
  Serial.println(SHT2x.GetDewPoint());

  delay(1000);
}


texts: Controlling servo with IR led and photodiode

texts: I have found myself a really nice scheme of a buzzer that is controled by the IR led and photodiode by I want to upgrade it so it can be used for controlling a servo. What I have in mind is that when there is no object the servo whould stand still and when object comes by it will go to 90 degrees, wait for 5 sec and go back to 0 position. I just want to know is that possible for an Arduino starter and where should I look for help. Thanks.


texts: How can I split a string into multiple parts?

texts:
I currently gather a string via bluetooth to my arduino and the string only has 5 different letters. "HELLO". I now wish to store these individual letters in a string on their own. Right now i have this code:

First I create a single string:

String readString;

Then I read my BTLEserial which is where I get the value that is being sent to the arduino and i store it in my string:

char c = BTLEserial.read();
readString += c;

readString now has the value "HELLO". Now i want to split it and what I have tried is to do it like this:

String stringOne = readString.substring (0,1); //H
String stringTwo = readString.substring (1,2); //E
String stringThree = readString.substring (2,3); //L
String stringFour = readString.substring (3,4); //L
String stringFive = readString.substring (4,5); //O

But with this i do not get the correct values in each string.

Appreciate every help I can get! :)


texts:
I'm using an Adafruit V1 Motor Shield for coding two 12 volt DC motors. In my code I'm changing the set speed, but the motors still seem to be going the same speed, which is really fast, and I want them to go slow.  What do I change to make my motors speed run the way I want them to run?
Here's my code below:
#include <AFMotor.h>

AF_DCMotor motor1(1);
AF_DCMotor motor2(2);

void setup() {
  Serial.begin(9600); // set up Serial library at 9600 bps
  Serial.println("Motor test!");
  // turn on motor
  motor1.setSpeed(3);
  motor2.setSpeed(5);
}

void loop() {
  uint8_t i;

  //second motor
  Serial.print("tick");

  motor2.run(FORWARD);

  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  Serial.print("tick");

  motor2.run(FORWARD);

  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  Serial.print("tick");

  motor2.run(FORWARD);

  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  Serial.print("tick");

  motor2.run(FORWARD);

  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  Serial.print("tick");

  motor2.run(FORWARD);

  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  //1 motor
  Serial.print("tick");

  motor1.run(FORWARD);

  for (i=0; i<255; i++) {
    motor1.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor1.setSpeed(i);
    delay(10);
  }

  Serial.print("tick");

  motor2.run(FORWARD);

  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  Serial.print("tick");

  motor2.run(FORWARD);

  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  Serial.print("tack");

  motor1.run(BACKWARD);

  for (i=0; i<255; i++) {
    motor1.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor1.setSpeed(i);
    delay(10);
  }
}


texts:
I have a simple circuit: detect that a person is walking towards the circuit (with HC-SR04), measure distance, light diodes (a wave effect) according to that distance – the closer, the faster the led wave.

When no person detected, sleep longer:

LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF);

When person detected, sleep shorter (so that diodes can be often turned on/off):

LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_OFF);

Without LowPower use – delay() used instead – the current taken is 15 mA. This is with diodes off. After using LowPower – it's still ~15 mA. This is very disappointing. I've expected the battery to last at least for 3 months, but it (9V) was drained within hours. Am I missing something?

Also a curiosity: the execution was fully blocking itself on LowPower calls, I've had to add short delay() before the calls, then they don't block execution.

#include <LowPower.h>
#include <NewPing.h>

#define trigPin 13
#define echoPin 12

NewPing sonar(trigPin, echoPin, 250);

// Defines speed of LEDs traversal
int delayTime = 40;

// Current led
int currentLED = 0;

// Direction of travel over LEDs
int dir = 1;

// Stores the last time LEDs were changed
unsigned long timeChanged = 0;

// Stores the last time sensor was read
unsigned long timeOfQuery = 0;

// LEDs
byte ledPin[] = { 4, 5, 6, 7, 8, 9, 10, 11 };

// Stores if any diodes are on
int leds_used = 1;

// Stores if wave is active
int off = 1;

// 5 last distances, circular buffer;
long distances[7] = { 400, 400, 400, 400, 400, 400, 400 }, currentDistance = 0;

// Last chosen distance
long distance = 400;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  for (int x = 0; x < 8; x++) {
    pinMode(ledPin[x], OUTPUT);
  }
  timeChanged = millis();
}

void loop() {
  long duration, cur_time, cm;

  cur_time = millis();

  /* Read distance when off, or when some time passed */
  if (off || (!off && (cur_time - timeOfQuery) > 100)) {
    timeOfQuery = cur_time;

    cm = sonar.ping_cm();
    if ( cm == 0 ) {
      cm = 400;
    }

    distances[(++currentDistance) % 7] = cm;
    // At least 1 proper distance?
    off = 1;
    for (int i = 0; i < 7; i++) {
      if (distances[i] <= 200) {
        off = 0;
        // Remember minimum distance
        if (distances[i] < distance) {
          distance = distances[i];

        }
      }
    }
    delayTime = distance;
  }

  if (!off) {
    // Check whether it has been long enough
    if ((cur_time - timeChanged) > delayTime) {

      // Turn off all of the LEDs
      for (int x = 0; x < 8; x++) {
        digitalWrite(ledPin[x], LOW);
      }

      // Turn on the current LED
      digitalWrite(ledPin[currentLED], HIGH);

      // Mark that diodes are being used
      leds_used = 1;

      // Increment by the direction value
      currentLED += dir;

      // If we are at the end of a row, change direction
      if (currentLED == 7) {
        dir = -1;
      }
      if (currentLED == 0) {
        dir = 1;
      }

      // Store the current time as the time we last changed LEDs
      timeChanged = cur_time;
    }

    // Shorter delay when sleeping
    delay(5);
    LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_OFF);
    //delay(50);
  } else {
    if (leds_used) {
      // Turn off all of the LEDs
      for (int x = 0; x < 8; x++) {
        digitalWrite(ledPin[x], LOW);
      }
      currentLED = 0;
      dir = 1;
      leds_used = 0;

      // Store the current time as the time we last changed LEDs
      timeChanged = cur_time;
    }

    // Longer delay when sleeping
    delay(10);
    LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF);
    //delay(200);
  }

  /*
    if (distance >= 200 || distance <= 0) {
      Serial.print(distance);
      Serial.println(" Out of range");
    }
    else {
      Serial.print(distance);
      Serial.println(" cm");
    }
  */
}

Update: The board is Arduino UNO.


texts: A question about Continuous Rotation Servo and Arduino

texts:
We have this project that uses a Continuous Rotation Servo and we have a slight problem controlling it. We're planning to attach a Rack Gear to the Servo to slide a stainless steel to the right, and vice versa.

The Question: Is it possible to stop the continuous rotation servo when the stainless steel hits a bump or it already made its proper position accurately?

This idea is like the Power Windows of cars.