texts: How to send a number to Arduino via Python over serial?

texts:
I call an API in Python and it gives as output as a single digit and an Arduino program receives this number over serial and displays it on a 7-segment display.

I wrote a different program in which Arduino sends the data and a Python program receives it. That worked but the following program is not working. What is the problem?

I am using Python 3 and Arduino Uno.

Python program:

import serial ,requests, json, time
arduino = serial.Serial('COM1', 9600, timeout=.1)
time.sleep(1)
response = requests.get("https://traffic.cit.api.here.com/traffic/6.1/flow.json?bbox=12.9808%2C77.5759%3B12.9803%2C77.5767&app_id=zbvY0tdRs089c3ZTKqWR&app_code=pxAtGksNBgVD9V5XF5nEzA",)
#CALLING API
response.content.decode("utf-8")
data = response.json()
text = str(data) #CONVERSION TO STRING
l = len(text)
for i in range(0,l): #Taking out the number
    if text[i] == 'J':
        j = text[i + 5]
        print (j)
        arduino.write(j) #writing over serial
        break

Arduino program:

int a=2;
int b=3;
int c=4;
int d=5;
int e=6;
int f=7;
int g=8;
int h=9;
int rx_byte = 0;

void setup() {
  Serial.begin(9600);
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(e, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(g, OUTPUT);
  pinMode(h, OUTPUT);
  digitalWrite(h, 0);  // start with the "dot" off
}

void loop() {
  if (Serial.available() > 0) {
    rx_byte = Serial.read(); //reading serial
    switch (rx_byte) {
    case 0:
      zero();
      break;
    case 1:
      one();
      break;
    case 2:
      two();
      break;
    case 3:
      three();
      break;
    case 4:
      four();
      break;
    case 5:
      five();
      break;
    case 6:
      six();
      break;
    case 7:
      seven();
      break;
    case 8:
      eight();
      break;
    case 9:
      nine();
      break;
    }
  }
}

// write '9'

void eight() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 1);
  digitalWrite(f, 1);
  digitalWrite(g, 1);

}
void seven() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 0);
  digitalWrite(e, 0);
  digitalWrite(f, 0);
  digitalWrite(g, 0);

}
void six() {
  digitalWrite(a, 1);
  digitalWrite(b, 0);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 1);
  digitalWrite(f, 1);
  digitalWrite(g, 1);
}
void five() {
  digitalWrite(a, 1);
  digitalWrite(b, 0);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 0);
  digitalWrite(f, 1);
  digitalWrite(g, 1);

}
void four() {
  digitalWrite(a, 0);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 0);
  digitalWrite(e, 0);
  digitalWrite(f, 1);
  digitalWrite(g, 1);
}
void three() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 0);
  digitalWrite(f, 0);
  digitalWrite(g, 1);

}
void two() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 0);
  digitalWrite(d, 1);
  digitalWrite(e, 1);
  digitalWrite(f, 0);
  digitalWrite(g, 1);
}
void one() {
  digitalWrite(a, 0);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 0);
  digitalWrite(e, 0);
  digitalWrite(f, 0);
  digitalWrite(g, 0);

}
void zero() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 1);
  digitalWrite(f, 1);
  digitalWrite(g, 0);

}
void nine() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 0);
  digitalWrite(e, 0);
  digitalWrite(f, 1);
  digitalWrite(g, 1);

}

I am quite new to programming. Please help.


texts: Read Arduino Serial from python for ulterasonic real time

texts:
I have a problem with Arduino serial and Python. I want to read data from my Arduino via Python and plot it out in real time but I'm getting delayed results.
This is the code running on my Arduino:
int trig = 7;
int echo = 6;
float T;
float c = 331.4; // sound speed meter per second
float d;
int distance;
void setup() {
Serial.begin(115200);
Serial.setTimeout(.1);
pinMode(trig,OUTPUT);
pinMode(echo,INPUT);

}

void loop() {
digitalWrite(trig,LOW);
delayMicroseconds(2);
digitalWrite(trig,HIGH);
delayMicroseconds(10);
digitalWrite(trig,LOW);
delayMicroseconds(10);
T = pulseIn(echo,HIGH);
//T = T/1000000;
distance = (T/2)*(c/10000);
//d = c*T;
//d = d*100;
Serial.println(distance);
//delay(50);
}

And this is my Python code:
import  serial
import matplotlib.pyplot as plt
import numpy as np
import time
ArduinoData = serial.Serial(port='COM8', baudrate=115200)
# plt.close('all')
plt.figure()
plt.ion()
plt.show()
data = np.array([])
i=0
try:

    while 1<100:
        if (ArduinoData.inWaiting() == 0):
            continue
        a = ArduinoData.readline()
        a.decode()
        b = float(a[0:4])
        data = np.append(data,b)
        plt.cla()
        plt.plot(data)
        print(data[:-1])
        plt.pause(0.001)

        # time.sleep(0.05)

        i = i+1
    ArduinoData.close()
except:
    print("Error")

guys any idea?


texts:
How could the same code be used with different ADC channels?

const byte adcPin = 0;  // A0

const int MAX_RESULTS = 100;

volatile int resultsV [MAX_RESULTS];
volatile int resultsI [MAX_RESULTS];

volatile int resultNumber;

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

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);
  OCR1A = 338;
  OCR1B = 338;   // 39 = 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
  //  ADCSRA |= (1 << ADPS1) | (1 << ADPS0);    // 8 prescaler for 153.8 KHz
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering
}

// ADC complete ISR
ISR (ADC_vect)
{
  resultsV[resultNumber++] = ADC;

  //resultsI[resultNumber++] = ADC;

  if (resultNumber == MAX_RESULTS)
  {
    ADCSRA = 0;  // turn off ADC
  }
}

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

void loop () {

  while (resultNumber < MAX_RESULTS)
  { }

  for (int i = 0; i < MAX_RESULTS; i++)
  {
    Serial.print( resultsV);
    Serial.print("   ");
    Serial.print( resultsI);
    Serial.println();
  }
  resultNumber = 0;
  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF) | bit (ADPS2) | bit (ADATE);
  // turn ADC back on
}


texts:
I am currently developing an IoT device with arduino and i want to minimise the data payload. First i used json which is not very efficent in fixed messages (the format will always be the same). Then i found something like messagepack which also sounds nice but i think you could do even better with just binary. I hope to find something like that:

I have a message for example:

#BOOL#INT#INT#FLOAT#BOOL#STRING#

The position of this variables never change so i could represent the message in binary and i could save a lot of bytes. Is there any library which can de/encode such formats and generate messages from given values?

If not i think it would be very useful in further IoT devices!


texts: Can I use IR Transmitter/Receiver for heart beat detecting?

texts:
Specifically, I want to know if the KY-022 module and KY-005 module can be used for heart beat detecting according to this tutorial?

KY-005:

KY-022:

If so, can you please explain to me how can I achieve such thing with respect to the following:
1- Is there any kind of synchronization between transmitter/receiver?
2- How to get a stable analog value from the receiver?
3- The Correlation between Heart beat rate and the obtained values?

providing circuit sketch will be very helpful but not necessary.
Thanks in advance.


texts: How can I reduce the memory usage on my code?

texts:
I wrote this code to control my christmas tree. It takes up the majority of the memory on my Arduino Uno:

Sketch uses 31822 bytes (98%) of program storage space. Maximum is 32256 bytes.
Global variables use 1882 bytes (91%) of dynamic memory, leaving 166 bytes for local variables. Maximum is 2048 bytes.
Low memory available, stability problems may occur.

Does anyone know how I can reduce the memory usage?

Code:

#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <SFEMP3Shield.h>

#define TREEONE 3
#define TREETWO 4
#define TREETHREE 5
#define TREEFOUR 10

SdFat sd;
SFEMP3Shield MP3player;

const uint8_t volume = 10; // MP3 Player volume 0=max, 255=lowest (off)
//10 for basement 50 for testing

const uint16_t monoMode = 1;

int song = 3;
int num = 0;
int count = 0;

//put arrays here
byte arrayTree[] = {17,16,9,8,3,2,5,4,17,16,9,8,3, ...etc };

void setup() {
  initSD();
  initMP3Player();

  pinMode(TREEONE, OUTPUT);
  pinMode(TREETWO, OUTPUT);
  pinMode(TREETHREE, OUTPUT);
  pinMode(TREEFOUR, OUTPUT);

  digitalWrite(TREEONE, HIGH);
  digitalWrite(TREETWO, HIGH);
  digitalWrite(TREETHREE, HIGH);
  digitalWrite(TREEFOUR, HIGH);
}

void loop() {
  if(!MP3player.isPlaying()){
    MP3player.playTrack(song);
    MetallicaChristmas();
  }
}

void initSD() {
  if(!sd.begin(SD_SEL, SPI_HALF_SPEED))
    sd.initErrorHalt();
  if(!sd.chdir("/"))
    sd.errorHalt("sd.chdir");
}

void initMP3Player() {
  uint8_t result = MP3player.begin();
  MP3player.setVolume(volume, volume);
  MP3player.setMonoMode(monoMode);
}

void treeFunc() {
    //delay(arrayTimes[i]);
    num = arrayTree[count];

    //TREEONE
    if(num>15){
      if((num%2)==0){
        digitalWrite(TREEONE,HIGH);
      }else{
        digitalWrite(TREEONE,LOW);
      }
    }
    //TREETWO
    if((num%16)>7){
      if((num%2)==0){
        digitalWrite(TREETWO,HIGH);
      }else{
        digitalWrite(TREETWO,LOW);
      }
    }
    //TREETHREE
    if((num%8)>3){
      if((num%2)==0){
        digitalWrite(TREETHREE,HIGH);
      }else{
        digitalWrite(TREETHREE,LOW);
      }
    }
    //TREEFOUR
    if((num%4)>1){
      if((num%2)==0){
        digitalWrite(TREEFOUR,HIGH);
      }else{
        digitalWrite(TREEFOUR,LOW);
      }
    }
  count = count + 1;
}

void MetallicaChristmas()
{
  //event 1
  delay(670);
  treeFunc();
  delay(248);
  treeFunc();
  //event 2
  delay(116);
  treeFunc();
  delay(248);
  treeFunc();
  //event 3
  delay(100);
  treeFunc();
  delay(248);
  treeFunc();
  //event 4
  delay(132);
  treeFunc();
  delay(248);
  treeFunc();
  //event 5
  delay(125);
  treeFunc();
  delay(248);
  treeFunc();
  //event 6

  ...etc.


texts: How to calculate air velocity from wire resistance?

texts:
I want to construct a constant current hot wire anemometer. For this, resistance is the input of the Arduino. There is a relationship between wire resistance and air velocity.

How can I calculate velocity from wire resistance?


texts:
With these few lines I am able to attach my certificate, tell it to WifiClientSecure the certificate, start the wifi as well as the mosquito pubsubclient:

WiFiClientSecure espClient;
WiFi.begin(ssid, password);

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

PubSubClient mqtt_client(espClient);
mqtt_client.setServer(mqtt_server, 8883);
mqtt_client.setCallback(mqtt_callback);
espClient.setCertificate(ca_crt, ca_crt_len);

if (!mqtt_client.connected()) {
  mqtt_reconnect();
}

mqtt_client.loop();

With these lines I am able to connect to wifi, depending on which the closest station is:

ESP8266WiFiMulti wifiMulti;

wifiMulti.addAP("primary-network-name", "pass-to-primary-network");
wifiMulti.addAP("secondary-network-name", "pass-to-secondary-network");
wifiMulti.addAP("tertiary-network-name", "pass-to-tertiary-network");

wifiMulti.run();

How can I combine both? I.e, I am interested in sending data to secure MQTT over a set of possible wifi networks?


texts: Large(ish) strings failing to send over WiFi101 using WiFiServer

texts:
I've based a sketch off the vanilla WiFi101 server examples.

If I define a const char array like this:

const char HTML_index[] = "test";

The server works well.  However if I increase the char[] size to about 1,300 bytes the server fails to send a response.  The device (Feather M0 WiFi) doesn't lock up, I can continue to make HTTP requests and the serial console functions correctly, just no HTTP response.  The device and laptop (client) are both on the same WiFi AP so nothing weird there.

First I thought this was a memory issues, but as I'm using newer architecture and IDE using const should ensure the string is in FLASH.

So I then read some threads about buffer limits per response using other libraries: https://github.com/esp8266/Arduino/issues/3205

But again not sure how applicable this is to an ARM based system/ WiFi101 library.

Is there a limiting buffer size etc when sending HTTP data in my setup? Do I need to split the string up into smaller pieces and send multiple responses?  How could I go about debugging this situation?

Edit:
This is the example sketch my code is based off:
https://www.arduino.cc/en/Tutorial/Wifi101SimpleWebServerWiFi

Edit2: ok I think I know what's going on but can't test right now, will post an answer when I do.  I found this thread https://github.com/arduino-libraries/WiFi101/issues/163 which talks about SOCKET_BUFFER_UDP_SIZE.  So I looked through the WiFi101 src and found this:

#ifdef LIMITED_RAM_DEVICE
#define SOCKET_BUFFER_SIZE 64
#else
#define SOCKET_BUFFER_SIZE 1472
#endif

https://github.com/arduino-libraries/WiFi101/blob/master/src/utility/WiFiSocket.cpp

It's likely that my string was actually over 1472 bytes so this makes sense.

Edit3:
Found more references:

https://github.com/arduino-libraries/ArduinoHttpClient/issues/14

https://github.com/arduino-libraries/WiFi101/pull/116

So I take it the 1500 in WINC1500 could mean the buffer size.  Either way looks like there's a hardware buffer limit and responses larger than ~1400 bytes need to be chunked.


texts:
I'm not understanding what's going on with my Uno. I have a very simple piece of code. no peripherals are connected. Just a bare genuine uno. I program in VisualMicro for Visual Studio.

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

    char stringy[9] = { 0x7E, 0x00, 0x05, 0x08, 0x01, 0x44, 0x33, 0x04, 0x7B };

    for (int i = 0; i < 9; i++) {

        Serial.print(stringy[i]);
        //delay(300);
    }

    Serial.println("");
    Serial.print("done");
}

void loop()
{
    while (1) {  }
}

Without a delay of around 250msec or greater in the for loop, I don't get all the characters. In fact, without the delay, the code doesn't even finish executing. I only get the first character '~'. It doesn't seem to matter what my baud rate is.

This code runs fine without a delay on my Nano. What could possibly be the issue?


texts: GSM incoming bytes from UART not complete

texts:
I have used AT commands to read incoming bytes from serial buffer from SIM900A but I cannot get the complete message using the code below:

while(ss.available()>0)
{
 inChar=ss.read();
 inString+=inChar;
}

Serial.println("Received messaged: ");
Serial.println(inString);

inString="";

However this one below works:

if(ss.available()>0)
{
  inString=ss.readString();
}

Serial.println("Received messaged: ");
Serial.println(inString);

inString="";

I wonder what is the difference?


texts: Automatic subtle colour changing on ws2812b with arduino

texts:
I'm creating a wordclock and I'd like to change the ws2812b led strip color slowly, so that it fades from one colour to another. However, I'm new to arduino and I can't get it done and I also could not find anything on this anywhere (probably because of using the wrong keywords)

Currently I have a colour hardcoded like this:

void SwitchLED(int MyArray[], int n) {
     for (i = MyArray[0]; i < MyArray[0]+n; i++) {
          leds[i].setRGB((161,57,0);
     }
}

(The array in this code are the LEDs that will light up depending on the time I get from a ds3231).

So I would like a (random) starting colour to slowly change to another colour and so on. This in such a way that you will notice it only after a couple of minutes, so very slow and subtle.

I'm using the FastLED libary. I bit of help on this would be appreciated very much.


texts:
Greeting to all,
Newbie in the contraption above (Arduino nano -> 74HC595 -> LCD display); I would like some help from the experts.
I connect the 74HC595 to the LCD display using the 4 wires as described on the net.
I download one of the sample sketch and "voilà" the "World welcomed me".
But .... I would like to make use of Q0, Q1, Q2 and Q3 on the 595 for other functions like flashing an LED or connecting a 5V buzzer even if the lcd screen blink for a fraction of second.
ie.:

lcd.setCursor(0, 1);
lcd.print("Welcome to the world");

// flash the LED

delay(100);

lcd.setCursor(0, 1);
lcd.print("Welcome to the world");

Is it possible and (please) HOW?
Thank you for your support.
Eric


texts: How can Arduino know Wire.available() is true or false?

texts:
In this part of code

void readFrom(byte device, byte fromAddress, int num, byte result[]) {
  Wire.beginTransmission(device);
  Wire.write(fromAddress);
  Wire.endTransmission();
  Wire.requestFrom((int)device, num);
  int i = 0;
  while(Wire.available()) {
    result[i] = Wire.read();
    i++;
  }
}

How can Arduino know that Wire.availble() is true or false?

I thought that when the microcontroller "reads" the value from the sensor, in pieces of 8 bits, he reads from 0 (n) to 5 (n+5) at the I2C address of the MPU-6050, and when he increments 6 it finds nothing, but this is my conclusion, i am not sure about it.

I am studying how Serial.available works and how the circular buffer works for the data comunication, because available() inherits from the Stream utility class.

The entire code is the following taken from  this question

  #include <Wire.h> //The I2C library

int gyroResult[3], accelResult[3];

//Function for writing a byte to an address on an I2C device
void writeTo(byte device, byte toAddress, byte val) {
  Wire.beginTransmission(device);
  Wire.write(toAddress);
  Wire.write(val);
  Wire.endTransmission();
}

//Function for reading num bytes from addresses on an I2C device
void readFrom(byte device, byte fromAddress, int num, byte result[]) {
  Wire.beginTransmission(device);
  Wire.write(fromAddress);
  Wire.endTransmission();
  Wire.requestFrom((int)device, num);
  int i = 0;
  while(Wire.available()) {
    result[i] = Wire.read();
    i++;
  }
}

//Function for reading the gyros.
void getGyroscopeReadings(int gyroResult[]) {
  byte buffer[6];
  readFrom(0x68,0x1D,6,buffer);
  gyroResult[0] = (((int)buffer[0]) << 8 ) | buffer[1]; //Combine two bytes into one int
  gyroResult[1] = (((int)buffer[2]) << 8 ) | buffer[3];
  gyroResult[2] = (((int)buffer[4]) << 8 ) | buffer[5];
}

//Function for reading the accelerometers
void getAccelerometerReadings(int accelResult[]) {
  byte buffer[6];
  readFrom(0x53,0x32,6,buffer);
  accelResult[0] = (((int)buffer[1]) << 8 ) | buffer[0]; //Yes, byte order different from gyros'
  accelResult[1] = (((int)buffer[3]) << 8 ) | buffer[2];
  accelResult[2] = (((int)buffer[5]) << 8 ) | buffer[4];
}

void setup() {
  Wire.begin();            //Open I2C communications as master
  Serial.begin(9600);    //Open serial communications to the PC to see what's happening

  writeTo(0x53,0x31,0x09); //Set accelerometer to 11bit, +/-4g
  writeTo(0x53,0x2D,0x08); //Set accelerometer to measure mode
  writeTo(0x68,0x16,0x1A); //Set gyro to +/-2000deg/sec and 98Hz low pass filter
  writeTo(0x68,0x15,0x09); //Set gyro to 100Hz sample rate
}

void loop() {
  getGyroscopeReadings(gyroResult);
  getAccelerometerReadings(accelResult);

  Serial.print(gyroResult[0]);
  Serial.print("\t");
  Serial.print(gyroResult[1]);
  Serial.print("\t");
  Serial.print(gyroResult[2]);
  Serial.print("\t\t");
  Serial.print(accelResult[0]);
  Serial.print("\t");
  Serial.print(accelResult[1]);
  Serial.print("\t");
  Serial.print(accelResult[2]);
  Serial.print("\n");

  delay(50);
}

Minor Question

I am trying to undestand the difference between the register and the device address, but i did find anything on my book.


texts:
I am looking as a first project after some simple project kits, to make a watering system for my indoor plants. I have seen  a few projects on instructables, so I went to look for components. I am not sure how to power the pump from the Arduino.

My idea is the following:

A bucket of water with a water pump inside. An irrigation system linked to the pump, which then goes to all the plants. The pump linked to arduino which turns it on and off based on a timer.

The components that I will be using are an Arduino uno and:

DV12 subversive pump
Irrigation watering kit

Also I guess I will need some tube to connect the pump to the watering kit.

I am not sure how to connect and power the pump (12V) with the arduino. The arduino it self will be powered by a USB on a wall socket.


texts:
I am making a project on gsm module(sim 900a unofficial shield), when I will send a SMS led will turn ON. after uploading code, module works fine, and led turned ON after sending message. But when I power off sim900a and Arduino, and power on back, it's not working, led not power up after sending message, when I reupload sketches it is working fine, means every time after power off I need to upload code again, I am learning c and don't have much knowledge? Is my code right? Or some other fault?

#include <SoftwareSerial.h> //software serial library for serial communication b/w arduino & GSM

    SoftwareSerial mySerial(8, 9);//connect Tx pin of GSM to pin 8 of arduino && Rx pin of GSM to pin no 9 of arduino

    int led = 7;
    String message;

    void setup()
    {
      mySerial.begin(9600);   // Setting the baud rate of GSM Module
      Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
      delay(100);

      mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
      delay(1000);
      pinMode(led,OUTPUT);
      digitalWrite(led,LOW);
    }

    void loop()
    {
      if (mySerial.available()>0){
      message = mySerial.readString();
      }

      if(message.indexOf("ON") > -1){
          Serial.println("LED ON");
         digitalWrite(led,HIGH);
         }
        else if(message.indexOf("OFF") > -1){

          Serial.println("LED OFF");
          digitalWrite(led,LOW);

      }

      delay(10);
    }

Circuit diagram


texts: how to prevent IR signal to go through 3d printed plastic?

texts:
I'm working on two arduino (one a dock, the other one on a robot) communicating through a IR to let the latter know about its location.

I 3D printed a piece which goal was to channel the 3 IR led lights, to prevent them from overlapsing (exactly in the same manner as the Kobuki.

For a reason I don't know, the IR signals seem to go through  the 3D printed piece which doesn't seem to let visible light through.

I known that there is no 100% absorbant materials, and I know "black for visible lights" doesn't necessarily mean "black for IR lights".

I think my problem is more related to my lack of experience in the field. My question is : why do I get signals from a IR led channeled toward a location I am not in ?

Patently, it means my light channels are not channeling light.

Therefore, better : How can I make a better (and cheap) channel for IR light ?

The piece I 3D printed is grey (silvery like I guess)

edit : to prevent incomprehension, i would like to clarify "channel". What I mean is to block all light "not going" in the right direction, whatever happens to that light. I apologize if it is not the word I should have used.


texts: Can you save data to EEPROM using firmata?

texts:
I have a few Arduino boards connected to my computer running firmata and I want the computer to be able to differentiate between them even when I unplug them and plug them back into a different USB port in a different sequence. My solution was to save and read a Unique I.D. into each Arduino's EEPROM, but I am not sure how to accomplish this using firmata?

I want to save a few bits of data to the Arduino UNO with EEPROM, but the Arduino has to be running code compatible with firmata. Is this possible?


texts: How to obtain four PWM outputs at 100 kHz using an arduino uno board? The requirement is that all four PWM outputs should have controllable duty ratios individually.


texts:
I am looking at the following code and getting confused by a few elements in it:

1) Why is there a writeto function being performed to the memory locations x053,0x31,x09 for accelerometer and 0x68,0x16 and 0x1A for gyro? We are only reading incoming values so what is the purpose of these functions?

2) the bitwise operation being performed in the getGyrscopeReadings and getAccelerometerReadings... are these operations to define how many bits data we will be reading?

    #include <Wire.h> //The I2C library

int gyroResult[3], accelResult[3];

//Function for writing a byte to an address on an I2C device
void writeTo(byte device, byte toAddress, byte val) {
  Wire.beginTransmission(device);
  Wire.write(toAddress);
  Wire.write(val);
  Wire.endTransmission();
}

//Function for reading num bytes from addresses on an I2C device
void readFrom(byte device, byte fromAddress, int num, byte result[]) {
  Wire.beginTransmission(device);
  Wire.write(fromAddress);
  Wire.endTransmission();
  Wire.requestFrom((int)device, num);
  int i = 0;
  while(Wire.available()) {
    result[i] = Wire.read();
    i++;
  }
}

//Function for reading the gyros.
void getGyroscopeReadings(int gyroResult[]) {
  byte buffer[6];
  readFrom(0x68,0x1D,6,buffer);
  gyroResult[0] = (((int)buffer[0]) << 8 ) | buffer[1]; //Combine two bytes into one int
  gyroResult[1] = (((int)buffer[2]) << 8 ) | buffer[3];
  gyroResult[2] = (((int)buffer[4]) << 8 ) | buffer[5];
}

//Function for reading the accelerometers
void getAccelerometerReadings(int accelResult[]) {
  byte buffer[6];
  readFrom(0x53,0x32,6,buffer);
  accelResult[0] = (((int)buffer[1]) << 8 ) | buffer[0]; //Yes, byte order different from gyros'
  accelResult[1] = (((int)buffer[3]) << 8 ) | buffer[2];
  accelResult[2] = (((int)buffer[5]) << 8 ) | buffer[4];
}

void setup() {
  Wire.begin();            //Open I2C communications as master
  Serial.begin(9600);    //Open serial communications to the PC to see what's happening

  writeTo(0x53,0x31,0x09); //Set accelerometer to 11bit, +/-4g
  writeTo(0x53,0x2D,0x08); //Set accelerometer to measure mode
  writeTo(0x68,0x16,0x1A); //Set gyro to +/-2000deg/sec and 98Hz low pass filter
  writeTo(0x68,0x15,0x09); //Set gyro to 100Hz sample rate
}

void loop() {
  getGyroscopeReadings(gyroResult);
  getAccelerometerReadings(accelResult);

  Serial.print(gyroResult[0]);
  Serial.print("\t");
  Serial.print(gyroResult[1]);
  Serial.print("\t");
  Serial.print(gyroResult[2]);
  Serial.print("\t\t");
  Serial.print(accelResult[0]);
  Serial.print("\t");
  Serial.print(accelResult[1]);
  Serial.print("\t");
  Serial.print(accelResult[2]);
  Serial.print("\n");

  delay(50);
}

any help would be greatly appreciated!


texts:
As is known, the speed of sound depends of temperature and Relative Humidity. I'm trying to calibrate HC-SR04 sensor taking account these factors.

In SparkFun page there is no mention about environmental conditions in calibration (only is informed that speed of sound is 340 m/s). I found a paper with some calibration, but again it is no mention of original conditions.

I'm using the time elapsed per response to calculate distance in Arduino with access to a temperature & humidity chamber, so I want to recreate the calibration conditions to probe if the sensor is accurate.

Anyone know the environmental conditions of HC-SR04 calibration?


texts: Can I corrupt my Arduino if it's unplugged during an upload?

texts:
When messing around with code and uploading a sketch to my Arduino board, I almost accidentally pulled out the USB cord. Everything is fine, but then I started thinking what would've happened if I had pulled it out.

How safe is avrdude? Could it damage or brick the board? I'd imagine that you would just have to upload code to it again... but what would happen before you upload the new code? I've seen something about how you can always upload new code if the bootloader is intact, but I would imagine that there would be some problems. If this were to happen, should I unplug everything connected in case Arduino writes a HIGH to an input (or similar) that would damage the component?


texts:
Has anyone seen or know of a method of preloading (using a computer or whatever) a firmware as data onto one arduino set up to operate as an isp and then using that arduino plug the isp interface into another and upload the firmware.

To be clear - i'm looking for a way to make uploading arduino sketches possible without a direct connection to a full blown computer.

Ideally the steps involved would be:

Write new sketch/firmware
Compile firmware
Write a copy firmware onto Arduino A as data (Arduino A is set up to work as ISP)
Detach Arduino A from the computer
In a seperate location attach Arduino A to Arduino B using ISP headers
Using some method (maybe a pushbutton) trigger Arduino A to upload the preloaded firmware onto Arduino B.

I'm assuming that theoretically it could work because uploading firmware is just an exchange of bytes across the SPI interface but i'm not sure about the reality.

The scenario for which I'm considering is if I were to install an arduino (permanently) in a location that is remote from my computer (I don't have a laptop nor do I want to get one) it would be troublesome to reprogram it.

The other method I have considered is using the DIL packaged ATMEGA which I can then remove from the board and program at the computer and return to the board - however I would much prefer not to risk bending of pins and the hassle of having to remove the chip each time I want to reprogram.


texts: file directory for saving .cpp & .h for the Arduino IDE for short #include statement

texts: I am trying to write a class/function that I think I will be using often in my Arduino IDE, I know the code but where should i save the file so that the IDE picks it up without a full directory address in the #include line, as you may guess I'm a little new to this....


texts:
When I plug the USB cable to my Arduino and try to upload a sketch I get thtis error:

avrdude: ser_open(): can't open device "/dev/cu.usbmodem1411": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

when I go to Tools > ports I can't find the USB port.
The Arduino still working and green ligh is on, so what is the problem exactly?


texts: Connect 12v DC sensor to Arduino UNO using TTL RS485

texts:
I'm trying to connect Arduino Uno with BGT PM2510 sensor (which uses 7-12V DC) by using UART TTL to RS485 Two-way Converter.
The only thing I wonder is can the sensor damage the MCU ?
According to the information on 12v sensor, it says:
Output signal: RS485 (Modbus protocol), I did measurement on A & B port of that sensor, the multimeter shows 3.3V.
My question is, can the sensor damage the MCU. I intend to connect Arduino & sensor as the diagram below:

Thank you,


texts: Python - Arduino communication not reliable

texts:
I'm trying to establish basic communication between python and my arduino due. I have managed to get a message sent to the arduino and sent back, but the code that achieves this task does not give consistent results. I'm running python 3.5 with pyserial 3.3.

My Arduino Code:

String incoming;

void setup() {
        Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
}

void loop() {

        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incoming = Serial.readStringUntil('\n');

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incoming);
        }
}

My Python Code

import serial

arduinoSerialData = serial.Serial("COM5",9600,timeout=1)

print("Initial in waiting:")
print(arduinoSerialData.in_waiting)
print("Initial out waiting:")
print(arduinoSerialData.out_waiting)

while (arduinoSerialData.in_waiting>0):
    garbage = arduinoSerialData.readline()
    print(garbage)

nummessages =0

while (nummessages<5):
    if (arduinoSerialData.in_waiting>0):
        myData = arduinoSerialData.readline()
        myData = myData.decode('utf-8')
        myData = myData.strip()
        print("The Arduino says:")
        print(myData)
        nummessages=nummessages+1
    elif(arduinoSerialData.out_waiting>0):
        pass
    else:
        arduinoSerialData.write(b'Hello Arduino!\n')

while (arduinoSerialData.in_waiting>0):
    garbage = arduinoSerialData.readline()
    print(garbage)

print("In Waiting: ")
print(arduinoSerialData.in_waiting)
print("Out Waiting: ")
print(arduinoSerialData.out_waiting)
arduinoSerialData.close()

These print statements are largely my failed attempt to diagnose the problem. The "garbage" loops were my attempt to make sure conditions were as identical as possible when the python code starts up. If I start the arduino program running and then call this python program from my command line I get inconsistent results. Sometimes my first call to the python "works" and then others won't, sometime it works several times in a row, and that first line out output where it says "The Arduino Says: I" will have a varying amounts of the "I Received: Hello Arduino" message the arduino was supposed to send. Any Ideas what could be causing this lack of consistency? If I try starting the python code first, the arduino can't even start up.


texts:
I want my Arduino Nano to consume as little power as possible, so I have been lowering the clock frequency with CLKPR from the default 16 MhZ speed. I successfully ran the program at 8 Mhz by setting CLKPR=0x01, but am unable to see any output in the serial monitor or any sign of the program running successfully at 4 Mhz (CLKPR=0x02). My project involves transmitting data between Arduino and an Android via Bluetooth, and I can see the receive LED blink on the Nano at 4 Mhz. However, for some reason it does not step through the code, and Serial monitor wont print statements. My Nano is a cheap knockoff so it's possible the chip is not designed to run at 4 Mhz. I've also tried the same test on a knockoff Uno and got the same results. Please let me know if you have any suggestions. I've included the code I'm trying to run:
int state = 0;
int stateData = 0;
int ultraPin = 10;
int trigPin = 11;    // Trigger
int echoPin = 12;    // Echo
long duration, cm;
unsigned char inches;
unsigned long timer;

void setup() {
  CLKPR = 0x80;
  CLKPR = 0x02; // 4 Mhz
  pinMode(ultraPin, OUTPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  digitalWrite(ultraPin, LOW);
  Serial.begin(9600*4); // multiply baud rate by inverse of clock frequency factor
}

void loop() {
  if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    stateData = Serial.read();
    if (stateData == 48){ // ON signal from phone
      Serial.write(50); // confirm signal received
      timer = millis();
      digitalWrite(ultraPin, HIGH);
      while (true){
          digitalWrite(trigPin, LOW);
          delayMicroseconds(2/4);
          digitalWrite(trigPin, HIGH);
          delayMicroseconds(10/4);
          digitalWrite(trigPin, LOW);
          pinMode(echoPin, INPUT);
          duration = pulseIn(echoPin, HIGH);
          cm = (duration / 2) / 29.1;   // Divide by 29.1 or multiply by 0.0343
          inches = (duration / 2) / 74; // Divide by 74 or multiply by 0.0135
          Serial.write(inches);
          delay(50/4);
          stateData = Serial.read();
          if (stateData != 49){
            // receipt from android
            unsigned long timeElapse = millis() - timer;
            if (timeElapse > 5000/4) {
              break;
            }
          }
          else {
              // reset the timer
              timer = millis();
            }
      }
    }
 }
 delay(200/4);
}


texts: How can an Arduino output a specific (i.e. 56 kHz) carrier frequency?

texts:
I'm working on a free space optics project to send data wirelessly between two points. To accomplish this I'm using an IR LED connected to an Arduino Uno that pulses with a 56 kHz carrier frequency for the transmitter and a second Arduino with a 56 kHz IR detector module for the receiver.

I tried using delayMicroseconds() between pin high and pin low commands in order to create the carrier frequency. This kind of works, but the frequency isn't always the same and any additional delays for pulsing the signal (i.e. the time required to call the function and decrementing) can change it.

Reading the datasheet for the ATmega328 it appears that there is a way to set a more accurate pulse using the chip's timers. Is that possible, and if so, how do you create a 56 kHz pulse using the timers?


texts: Problem uploading code to ESP 8266-01 adapter

texts:
I feel like I've tried just about everything and it still doesn't work. There must be something I'm not seeing. I am using an Arduino uno, an ESP8266-01 wifi module, and an ESP-01 Adapter. The arduino is connected to the laptop, and I'm using 4 AA batteries as external source (they are brand new) because I wanted to check if my Arduino wasn't supplying the necessary power.

I keep getting the following error:
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

I changed my preferences to add to the boards http://arduino.esp8266.com/versions/2.4.1/package_esp8266com_index.json

This is how I set up tools. I keep trying every upload speed whenever I make a change to see if that makes it work but nothing still.

I also tried using this tutorial but it also didn't work.

Any help would be appreciated :)


texts: Looking for offline or online Arduino stimulator or software contains Bluetooth or WiFi as input

texts:
I went through online stimulator Tinkercad.
I am looking for a stimulator which contain Bluetooth or WiFi as input.
If anyone has any idea please help


texts: Fastest communication between Arduino and PC

texts:
I am using an Arduino 2 which collects data from a set of microphones and stores it in an array of unsigned short of 40000 elements and sends them to the PC via Serial USB.

It is working but I'd like to obtain more speed without any errors.

Can you suggest me the best way to do it? Even changing communication.

Thank you


texts:
I have an Arduino Leonardo and a GPS module "NEO 6M"

Pinout:

PPS->free
rxd->11
txd->10
gnd->gnd
vcc->5v

I'm running this code:

#include "SoftwareSerial.h"
SoftwareSerial gps(10,11);
void setup(){
  Serial.begin(9600);
  gps.begin(9600);
}

void loop(){
  while (gps.available())
    Serial.write(gps.read());
}

In serial monitor I'm getting random characters like this

Where am I going wrong?

I tried the same with an Arduino Mega but have the same result.


texts: How do you remove an item from array arduino?

texts: Is there a way that can change {3, 5, 3, 6} to {3, 5, 6} with a function? I checked all the arduino forums but they don't give the answer i need (just delete 1 item from an array with a function like delete(myArray, 2)).


texts: Arduino UNO WiFi RestServer returning "not found"

texts:
I'm trying to run RestServer on my Arduino UNO WiFi, and I'm currently using the tutorial from Arduino: http://www.arduino.org/learning/tutorials/boards-tutorials/restserver-and-restclient

Everything works as expected, but whenever I change this:

  // is "digital" command?
  if (command == "digital") {
    digitalCommand(client);
  }

To this:

  // is "digital" command?
  if (command == "test") {
    digitalCommand(client);
  }

and go the the same URL but instead of "digital", user "test", I get a "not found" error.

(from http://url/arduino/digital/13/1 to http://url/arduino/test/13/1)

Am I doing something wrong? Or are the URLs in that example the only possible ones?


texts: What is the difference between a Hall effect sensor and an inductive one?

texts:
From what I have read, when placed within a magnetic field, a current will flow in both sensors.

My goal is to use this kind of sensors to guide a robot thanks to an existing automower loop wire, such as suggested in DIY Perimeter Wire Generator and Sensor.

I am thus wondering what is the difference between a Hall effect sensor and an inductive one such as the one described in the link above?


texts: Flash a .hex to an ATtiny45 with Arduino

texts:
I'm trying to upload a hex file to an ATtiny45 with an Arduino. I uploaded the Arduino ISP sketch to my board. I connected the ATtiny as shown below:

Then I go to CMD and type:

avrdude -c avrisp -p t45 -b 19200 -P COM6 -U flash:w:main.hex:i

And it gives me this error:

Please define PAGEL and BS2 signals for ATtiny45!

I double checked the connections and i tried to uplad a bootloader with Arduino IDE as written in this article: Programming Hex-code on an Attiny85 with the Arduino. I can uplad sketches with ArduinoIDE with no error.


texts: Two power source for Arduino and a relay

texts:
In my work, I have an ESP-8266, Arduino-Uno and a Relay. ESP 8266 and Uno is connected. Relay's data signal is take from arduino's 12th pin. ESP is powered from Uno.

If I use two different power sources for Uno and Relay, Relay does not response for the signal from Uno. (Both have a same common ground)

If relay is powered from Uno, then after load control (power on and off) ESP-8266 goes down.


texts: ACS712 Module inaccurate reading in some devices

texts:
I'm currently trying to isolate what's the problem with a current sensor build I'm working on right now. I'm using a ACS712 that can handle 30A, I've used the code at

http://henrysbench.capnfatz.com/henrys-bench/arduino-current-measurements/acs712-arduino-ac-current-tutorial/

And so far for certain devices like pencil sharpeners, computers, chargers, and other household devices the amperage readout seems is "correct" there's some minor error due to the noise I assume.. There's like .10 amperage difference. But when I plug in a stereo amplifier the error sky rockets to 1 Amp to even 2 Amps and I'm not quite sure what's the problem, I've also tried multiple codes online and all of them reach the same conclusion.

Thanks,


texts:
I just bought an Esp8266(not the node MCU) and tried connecting it with Arduino without a USB to serial converter but in vain. I am a beginner and don't know what to do. It is not responding to AT commands. Can anyone give me a detailed step by step process to connect it?
I am using Arduino UNO R3.
This is my connection diagram:-

I uploaded an empty code(Bare minimum example code), just to see if the AT commands are working, but it failed to respond. I reflashed it, then also it is not working.
when I type AT it shows nothing. But if I shake it, sometimes it shows gibberish.


texts: Why doesn't pin 19 work when powering the EzSBC Esp32 board from batteries?

texts:
I recently got an ESP32-01 Breakout and Development Board from EzSBC.com.  It is advertised as a board specifically designed for use with batteries because of it's low current draw when in sleep.

As a test I loaded the basic Arduino blink sketch onto the board using pin 19 as the built in test LED.  When I power the board from the computer through the USB connection the LED blinks as expected, but when I connect a battery accross VIN -> GND nothing happens.

What am I doing wrong?


texts: How to swap ground and power for multimeter

texts: I'm trying to create a multimeter that measures resistance and capacitance for a school project and the code must be under 30 lines. I have made both a resistance meter and a capacitance meter but the only problem is that on for my resistance meter, ground is connected to the to the known resistor and the arduino's output goes through the unknown component. Where as my capacitance meter is the opposite (ground to unknown, output to known), just wondering if their is an easy fix or if i need to rethink my entire project. Any help is appreciated, thanks.


texts: Receive data from multiple wireless sensors simultaneously

texts:
I want to receive data from multiple (2/3) wireless sensors at the 512 Hz data rate simultaneously at a single receiver (bluetooth or any other wireless standard). Is it possible with one receiver or I need  multiple receivers?

I am novice to wireless communication please guide me to any available resources.
Thank you.


texts: Wiring Feather Huzzah ESP8266 to Monochrome 1.3" 128x64 LCD

texts:
I'm new to Arduino and the pinouts for the Adafruit 938 LCD doesn't seem to match the pinouts that I looked up for the Huzzah ESP8266.

Does anyone know the proper pinout for this display and the Huzzah?


texts: Absolute encoder vs Accelerometer for calculating angles

texts:
I've been toying with this idea for a while and after some thorough research I'm more than happy that the project is realistic. However I'm in need of some direction in terms of the sensors I should be using.

There will be 3 arms all connected together (Like a poor mans Microscribe). I want to read the angle between each arm and use that info to calculate the final X and Y coordinates of the final end point on the arm.

I've looked closely into forward kinematics in robot arms and understand the principles are very much the same.

I've narrowed it down to Absolute encoders or accelerometers. Unfortunately I just can't find enough documentation about how to use the encoder with Arduino. There's plenty on using an accelerometer but I can't imagine the accuracy would be as good as the encoder.

I'm hoping to get the X and Y coordinate accuracy within +/- 0.5mm. Is this accuracy feasible?

The diagram attached shows the basic principle and formula I will use.

------EDIT-----

Thanks for the info everyone! Seems like this is going to be a little trickier than I originally thought. I've found a project achieving something very similar, however there's no mention of it's accuracy. http://fablab.ruc.dk/diy-digitizer/

Any ideas as to what sort of accuracy he could be achieving? I understand the length of the arms are considerably shorter than mine which must help a huge deal.


texts: Error: invalid application of 'sizeof' to incomplete type 'int []' when trying to compute the size of an array in a library

texts:
I have created a library that contains an array. This is the .h file:

class Lib {
  public:
    static int arr[];
};

And this is the .cpp file:

#include "Lib.h"

int Lib::arr[] = {0, 1, 2, 3};

When trying to compute the size of this array from within the library, it works just fine. When trying to do this from a sketch, I get the error mentioned in the title. This is the sketch I'm using:

#include <Lib.h>

void setup() {
  sizeof(Lib::arr);
}

void loop() {}

What is the problem here?


texts: I already have a button on my Arduino board, but I don't know what pin number should I use in my code?

texts:
I'm attaching a picture of my board which has the push button I want to use, but I cannot because I don't know what pin number should I write in my code.

my code:

int switchPin = Button;
int ledPin =13;

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

void loop() {
  // put your main code here, to run repeatedly:
if(digitalRead(switchPin) == HIGH)
{
  digitalWrite(ledPin, HIGH);
}
else
{
  digitalWrite(ledPin, LOW);
}
}

This is a picture shows the button on the top right "green"


texts: connecting RTC DS1307 to ethernet shield

texts:
What is the easiest way to mount DS1307 to ethernet shield?

I tried to do this:
https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/wiring-it-up

but my program just freezes when I try to read data from RTC. Is there any other ways to do it?

Code looks like this:

const int RTCpin2 = 2;
const int RTCpin3 = 3;

void setup() {
    pinMode(RTCpin2, OUTPUT);
    pinMode(RTCpin3, OUTPUT);

    analogWrite(RTCpin2, LOW);
    analogWrite(RTCpin3, HIGH);
}

void loop() {
     // process RTC time
}


texts:
I want to use the buzzer KPEG2000 in my Arduino application. I would like to know if a GPIO can directly drive this buzzer, without destroy the uC (a GPIO can deliver 40 mA max). In the datasheet, we can find the current consumption under 12 volts (40 mA), but if I decrease the driving voltage to 5V, will this buzzer use more or less then 40 mA ?

https://docs-emea.rs-online.com/webdocs/07a8/0900766b807a8e16.pdf

I already tried to make this buzzer work on an Arduino, and it works. But I would like to know if plugging this buzzer directly to the Arduino will not destroy it.


texts: Feasability of flashing Arduino UNO r3 with teensy firmware for HID (keyboard) emulation purposes

texts:
I've been working on a DIY keyboard project I have all the hardware designed and now its time for the code. For the microcontroller, I'm sort of locked into an Arduino UNO r3 as I already have it lying around. I know it doesn't have HID capabilities baked in, but I can flash different firmware to it. At first I was going to go with a generic HID firmware. This approach was problematic because it would require me to first write/send my Arduino sketch, then touch I wire to various portions of my UNO (it isn't SMD). After this,
I would flash the HID firmware and hope that there were no bugs in my sketch as fixing bugs would have required flashing Arduino firmware and repeating the aforementioned steps. I then had the idea to use Teensy firmware (https://www.pjrc.com/teensy/). This approach seems better, but I have questions regarding its feasibility.

Can I upload Teensy programs/sketches to the Arduino after I've
updated its firmware (if I had a real Teensy I could do this via the teensyduino plugin)?
Similarly, I'd like to write some software that allows me to remap
    the keyboard. Would the Teensy firmware allow this?
Does the Arduino have enough memory to support #2?
Is it possible to reflash BOTH the 8u2 and the 16u2 on my UNO (for details see #2 in update one below)
If 4 is possible is it possible to write code that would read/write the flash on the 8u2 as a filesystem? (for details see #2 in update one below)

Would the teensy firmware be a good option given these constraints? I know I've focused mainly on the Teensy, but if you have a more straightforward approach I'd love to hear it. Also, I know Arduino has a keyboard library(http://arduino.cc/en/Reference/MouseKeyboard) but, it seems rather basic, seems to block other keyboard signals while in use, and isn't easily remappable(see #2). I haven't completely written this off, so if you think this would be the best option please let me know. Thanks for any and all help.

Update
Thanks to one of the questions linked by @Ignacio Vazquez-Abrams(Can the 2nd MCU on the UNO R3 be used for keyboard emulation?) on the original question(weirdly it didn't show up here)  I have learned the following things(not necessarily from the question itself but by links provided in it):

the Atmel 8u2 of the UNO has 8kb of flash while the 16u2 has 16kb (should've known) I still don't know if either of these sizes are enough to hold my Teensy code AND 1+ map files generated by the mapping software I would make. (see #2 above)
the 8u2 seems like the chip that tinkers are generally advised to reprogram as it wouldn't hold the Arduino sketch. If I'm uploading teensy firmware I shouldn't need Arduino sketch capability (Teensy has that built in) So What I might do is use the 16u2 as a place to hold the firmware my code and use the 8u2 as a filesystem to hold any maps I'd like to store. This leads to more questions see the newly added 4 and 5


texts: AT Commands ESP8266 Arduino IDE serial monitor not print any data from server. It say 408 request timeout

texts:
i am new in arduino and ESP8266 module. I am still learning about AT command. But i found this problem:
1.My website code (index.html)-http://nyalalampu.atwebpages.com:

<?php
        ECHO $_GET['subject'];
?>

2.My AT commands (In Arduino IDE Serial Monitor)
AT+CIPSTART="TCP","nyalalampu.atwebpages.com",80

CONNECT

OK
AT+CIPSEND=29

OK
>
Recv 29 bytes

SEND OK

+IPD,391:HTTP/1.1 408 Request Timeout
Date: Sat, 10 Oct 2020 17:00:24 GMT
Server: Apache
Content-Length: 221
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>408 Request Timeout</title>

Request Timeout

Server timeout waiting for the HTTP request from the client.

CLOSED

After > i put
GET /?subject=anis HTTP/1.0

My question is why it not print anis in Arduino IDE Serial Monitor? It just show 408 Request Timeout
I hope someone can tell me what's wrong with my code.TQ


texts: Passive buzzer works with analogWrite(), but not with digitalWrite(). It also has constant static noise

texts:
I have a YL-44/MH-FMD passive piezo buzzer hooked up to an ESP8266/NodeMCU.

It's connected like this: Buzzer ---> NodeMCU
- GND ---> G
- VCC ---> 3V
- I/O ---> D2

This code makes a clear beep.

void loop() {
  analogWrite(BUZZER, 255);
  delay(100);
  analogWrite(BUZZER, 0);
}

This code makes a weird low clicking sound, no beep.

void loop() {
  digitalWrite(BUZZER, HIGH);
  delay(100);
  digitalWrite(BUZZER, LOW);
}

I have no idea why the second one doesn't work, as all the tutorials reference that one.

Also, why does the buzzer have a weird constant static noise and gets hot?

Am I doing something wrong in the wiring? I use no resistors, as the tutorials don't show that.


texts: Bitmap only displays correctly with PROGMEM keyword

texts:
I have a bitmap to draw defined as below.

PROGMEM const unsigned char ship1 [] = {0x18, 0x3C, 0x7E, 0xFF, 0x81, 0xC3};

It is then used by the arduboy library's draw slow bitmap function like so:

arduboy.drawSlowXYBitmap(5,5, ship1, 8 , 6, WHITE);

Can anyone explain to me why the bitmap only draws correctly with the PROGMEM keyword? I omitted it at first and it causes the bitmap to look completely different.

I see that this keyword makes the data get written to flash instead of SRAM.

The hardware I am using is the Arduboy.

The arduboy.drawSlowXYBitmap() function is from https://github.com/Arduboy/Arduboy

void Arduboy::drawSlowXYBitmap
(int16_t x, int16_t y, const uint8_t *bitmap, uint8_t w, uint8_t h, uint8_t color)
{
  // no need to dar at all of we're offscreen
  if (x+w < 0 || x > WIDTH-1 || y+h < 0 || y > HEIGHT-1)
    return;

  int16_t xi, yi, byteWidth = (w + 7) / 8;
  for(yi = 0; yi < h; yi++) {
    for(xi = 0; xi < w; xi++ ) {
      if(pgm_read_byte(bitmap + yi * byteWidth + xi / 8) & (128 >> (xi & 7))) {
        drawPixel(x + xi, y + yi, color);
      }
    }
  }
}

Imagine two programs identical apart from the PROGMEM keyword. The program only contains the lines mentioned above and the relevant calls to refresh the display. What I want an explanation of is why I get a garbled image without it and a fine image with it.


texts:
After a long afternoon, chasing a fault on my project, I've come to find that I've damaged 2 out of the 6 Analogue Inputs. Their ADC reading doesn't display 0 when grounded, nor a known ADC value from a sensor.

I've identified the problem to the voltage divider sensors that were connected to these particular Analogue Inputs, I've since researched that topic and made some alterations.

I don't suppose by buying a replacement chip, will solve the problem of 2 bad Analogue Inputs? So I can save the hardware and reduce cost?

Thanks in advance for any help you can provide.

Stu


texts: Connecting multiple component's VCC wires to one Arduino UNO R3 5V Pin

texts:
Apologies for the title gore and whether this seems to be a fairly basic question, I'm an Arduino noob.

I'm working on a wearable sensor system project at my university using an Arduino UNO R3 to handle all the sensors and power them. I'm currently powering the board with a USB connection and will be powering my components from the board's 5V pin as they can all safely operate with that voltage. The individual components do not exceed their I/O pins max current and their combined current usage doesn't exceed the boards maximum current.

My question comes in here: in the past if I've needed to connect multiple components to the ground and 5V pins of an Arduino board, I was always taught to use a matrix board to solder my component's 5V and GND wires to, where they could then be powered from two soldered wires from the microcontrollers 5V and GND pins.

Given that this is a wearable system, I would like to minimise any unnecessary hardware and so proposed to my supervisor that we cut out the matrix board and simply solder the VCC wires of the components together to one header pin which we can then plug into the 5V pin on the board to draw power. He strongly cautioned against this but wasn't able to provide a concrete reason as to why it would be a problem; as far as I can see the fundamental theory is the same and we are simply cutting out an unnecessary middle man.

Is there something I'm missing here or does this solution seem like it would work fine? Additionally, if this solution works for VCC, would the same principle work for sharing a grounded connection?


texts: GPS Module Outputting Question Marks in Serial Window

texts:
I've got a uBlox Neo 7N GPS Module and configured it so if theres is no incoming data print no location but if there is print the latitude and longitude. However it's printing ?,?.

So I'm assuming it's wired correctly as I'm getting an output however maybe my code is preventing it from printing the two long numbers hence converting it to a ? instead.

  char buf[128];
  if (gps.location.isValid()) {
    snprintf(buf, sizeof(buf), "%lf,%lf", gps.location.lat(), gps.location.lng());
    Serial.println(buf);
  }

EDIT I know that Im getting a read as I set two variables of type double lat and long to equal gps.location.lat() and gps.location.lng() respectively and I'm getting a number. How do I fix up this snprintf line so it prints properly?


texts:
I have 2x NRF24L01+ communicating but they are unreliable. It doesn't matter if they are right night to each other or 100ft away. For some odd reason when I place my hand on the antenna it work perfectly. Why would this be?
I have one set up to send and one to receive. All I am sending from one to the other is a 3 digit number to turn on a relay.


texts: A while ago I made a code for a drag timing system and uploaded it to my Arduino mega after that I broke my computer and got a new one and I don't have that code anymore. Does anyone know how to recover it from my Arduino?


texts: Arduino IDE menu doesn't display properly (missing letters)

texts:
I have just installed newest version of Arduino 1.7.10 from arduino.org.
It has this problem that its menu are not displaying properly - when I hover mouse over items in menu they either disappear completely or some of the letters are missing. Sometimes the whole menu (like 'tools' menu) won't even display. Dialog windows (like "Do you want to save your changes") also suffer from this problem.

I have Windows 7 and I just installed newest version of Java to see if this helps, but it doesn't.
Have any of you had such problem?


texts: Is it ok to share the same power rail for the arduino and a shield?

texts: I have a two amp 5VDC power rail.  I have configured a motor shield to use external DC (by moving a jumper.)  Is it ok to share the rail between the arduino's 5V and Gnd pins, and the motor shield?


texts:
I'm trying to understand the relationship between embedded RTOSes, SoCs and chip architectures. Specifically, I have a hobby project that would involve me writing a real-time, embedded application for the embox RTOS, and use Arduino hardware for my proof of concept/prototype. Then, budget permitting, I'd like to port that app to run on another, non-Arduino ARM-based system.

My understanding is that ARM is the chip architecture (a conceptual design, really), and that Arduino simply implements this design, and is also a "system on a chip" because it has other things (USB ports, GPIO pins, etc.) that make it more of a computer than just a MCU.

My understanding is that if embox runs on ARM, which they claim it does, then at some point in the future I can take my application and run it on another ARM-based system without any real headache/pain.

Is my understanding of: ARM, Arduino, MCU, SoC and embox/RTOS correct? If not, please clarify/correct me! If so, what sort of considerations would have to be made when porting my app to another ARM system in the future?


texts: Processing error with processing-arduino examples

texts:
I have followed the instructions to run the Arduino processing examples but with no success.

Always import processing.serial.*; does not name a type. Which is perhaps a library (processing-arduino) related error.

My sketch is a sketch that comes with processing-arduino library.

I have searched for a long time with no solution. Any suggestion?

Errors:

arduino_output:28: error: 'import' does not name a type
arduino_output:30: error: 'import' does not name a type
arduino_output:32: error: 'Arduino' does not name a type
arduino_output:34: error: 'color' does not name a type
arduino_output:35: error: 'color' does not name a type
arduino_output:37: error: expected unqualified-id before '[' token
arduino_output.pde: In function 'void setup()':
arduino_output:42: error: 'size' was not declared in this scope
arduino_output:45: error: 'Arduino' was not declared in this scope
arduino_output:45: error: 'println' was not declared in this scope
arduino_output:50: error: 'arduino' was not declared in this scope
arduino_output:50: error: expected type-specifier before 'Arduino'
arduino_output:50: error: expected `;' before 'Arduino'
arduino_output:58: error: expected unqualified-id before numeric constant
arduino_output.pde: In function 'void draw()':
arduino_output:62: error: 'off' was not declared in this scope
arduino_output:62: error: 'background' was not declared in this scope
arduino_output:63: error: 'on' was not declared in this scope
arduino_output:63: error: 'stroke' was not declared in this scope
arduino_output:66: error: 'values' was not declared in this scope
arduino_output:66: error: 'Arduino' was not declared in this scope
arduino_output:66: error: expected unqualified-id before numeric constant
arduino_output:66: error: expected `)' before numeric constant
arduino_output:67: error: 'fill' was not declared in this scope
arduino_output:69: error: 'fill' was not declared in this scope
arduino_output:71: error: 'rect' was not declared in this scope
arduino_output.pde: In function 'void mousePressed()':
arduino_output:77: error: 'mouseX' was not declared in this scope
arduino_output:80: error: 'values' was not declared in this scope
arduino_output:80: error: 'Arduino' was not declared in this scope
arduino_output:80: error: expected unqualified-id before numeric constant
arduino_output:80: error: expected `)' before numeric constant
arduino_output:81: error: 'arduino' was not declared in this scope
arduino_output:81: error: expected unqualified-id before numeric constant
arduino_output:82: error: expected unqualified-id before numeric constant
arduino_output:82: error: expected `;' before numeric constant
arduino_output:84: error: 'arduino' was not declared in this scope
arduino_output:84: error: expected unqualified-id before numeric constant
arduino_output:85: error: expected unqualified-id before numeric constant
arduino_output:85: error: expected `;' before numeric constant


texts:
I am working from the example sketch in that installed with the ESP32 Dev Module into the Arduino IDE.  It includes <WiFi.h> and "time.h".  I have a number of questions about how to use the clock that is set up with configTime using NTP. I am trying to find the documentation, but I'm having difficulty identifying exactly who is providing me the "time.h" header file, and of course, there are a lot of different time.h header files out there so googling is difficult.

Where can I find the documentation for this particular header?

Example questions:

Can the time be set manually without a WiFi connection?
Can the timezone be changed without connecting to NTP again?
Can I get the time as a Unix Time Stamp?  (Yes)
Can I arrange for a function callback at a certain time? (I'm aware I can use the timer library for this but I'm hoping for something like a callback at 4:20p every Saturday)


texts: Trigger ESP8266 reset pin on broken connection

texts:
I have an ESP8266 which I wish to place in deep sleep until a reed switch senses a door being opened. The ESP8266 is woken from deep sleep by briefly raising the RESET pin high.
In my original design, I thought that raising the RESET pin would wake the device instantly. Instead raising the pin holds the device in a reset state until it goes low again. This means that the 8266 currently wakes after the door is opened and closed again.
I'm looking for a way to briefly trigger the RESET pin after the reed switch connection is broken with minimal additional hardware, and minimal power drain while in deep sleep. I can use either NC or NO Reed switches.
Any suggestions?


texts:
Something I'd like information on is whether it is possible to upload a SPIFFS filesystem image to the ESP8266. In theory it might work: It can be uploaded over USB, and according to the logs the flash location changes, but that's about it. PlatformIO also seems to offer an Upload SPIFFS option in a platform that's set to an OTA port, but that could just be it not checking the upload type.

So, what I want to know is how I can configure (or otherwise make) a SPIFFS image OTA-uploadable. I have two main OTA methods: Option One is the default Arduino OTA library, and Option Two is a re-skin of the OTA method-whose-name-is-forgettable where I can upload a file on a webpage hosted by the ESP8266 and it will read the file and update its firmware.

I'm assuming that there's a configuration parameter for this somewhere, but I don't know where to start looking, and the documentation on these libraries has a few very basic examples that don't cover complex or advanced use cases.

(The web server--though essentially unrelated to this issue, it's a great example--is the most egregious of these; the code is complex and now templated too, so I can't make sense of it, and the "examples" consist largely of compressed javascript that doesn't show the user anything. Then you get to the interesting stuff like actually getting the real size of an uploading file, or want to know how uploading things actually works (or why it fails), or you want to serve a file piecemeal by assembling bits of text (in the same way that debug statements usually make use of multiple Serial.print() statements), and there's just nothing)


texts:
I am working on a school project, basically I have to create a lock system that opens a fictive gate when the correct code is entered. We have been asked to simulate our system before actually building it. So, I made the following circuit in Proteus(Labcenter Electronics' simulation software):

Here's what my system should do: A variable contains the correct code and the user must type a code on the keypad, and if it is correct, a green LED turns on and the LCD screen displays "Acces Granted!" if the code is wrong, the screen will display "Access refused!". It's a basic system, but I'm trying to make it as simple/short as possible(I have to explain it in an oral presentation, so the simpler the better) and for some reason, I can't get my code to work. Ideally, I'd like to have the LCD display a * for each character typed, liked on a real security system, but I haven't managed to do that either. I've been working on it for hours, trying different variants and etc.. but nothing seems to work the way I want to. BTW, my circuit works perfectly fine and the initialisation part of my code is therefore correct as well. Can anyone help me figure out what's wrong with my code and how I can make it better?

Here's my code so far:

#include <LiquidCrystal.h>
#include <Keypad.h>

//define LED pins
#define redLED 11
#define greenLED 10

String codeSerrure = "87362";   //correct code that opens the imaginative gate
String enteredCode = "";
int keyPressed;

const byte rows = 4;
const byte cols = 3;

char touches_digicode [rows] [cols] = {

  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins [rows] = {25, 26, 27, 28};
byte colPins [cols] = {24, 23, 22};

Keypad leDigicode = Keypad( makeKeymap(touches_digicode), rowPins, colPins, rows, cols);
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

void setup(){
  lcd.begin(16, 2);
  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  digitalWrite(redLED, HIGH);
}

void loop(){
  lcd.setCursor(0,0);
  lcd.print(" Entrez le code");

  keyPressed = leDigicode.getKey();
  enteredCode += String(keyPressed);
  if(enteredCode.length() >= 5){
    if(enteredCode == codeSerrure){
      digitalWrite(greenLED, HIGH);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("  Acces autorise!");
      delay(4000);
      digitalWrite(greenLED, LOW);
      digitalWrite(redLED, HIGH);
      enteredCode = "";
    }
    else{
      digitalWrite(redLED, HIGH);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("  Acces refuse!");
      delay(4000);
      enteredCode = "";
    }
  }
  if(keyPressed == "#"){
    lcd.clear();
    enteredCode = "";
  }
}

The problem is that when I run this code in the simulation software, the LCD displays "Acces refuse!" and the red LED is on. No matter what keys I press (on the keypad) nothing happens. So the problem is that my code jumps straight to the else statement, inferring that the password typed is wrong (although no password was actually typed). I think the error is in here:

keyPressed = leDigicode.getKey();
  enteredCode += String(keyPressed);
  if(enteredCode.length() >= 5){
    if(enteredCode == codeSerrure){

Btw, forgive the french words, I am french. Also, I forgot to say, the # key should, clear the entered code. Any explanations, code samples or links would help.


texts: Dimmer on Due: digitalWrite on one pin affects digital value of another

texts:
I'm trying to make dimmer for heater using Arduino Due. I'm using a variant of this very common scheme:

My scheme has MOC3043 with zero-crossing detection.

I use two pins to control the dimmer: detectorPin to analyse input voltage wave and controlPin to drive optocoupler. The program is very simple thanks to zero-crossing MOC.

I attached an interrupt to the input detectorPin on CHANGE event. And controlPin is used as digital output. When I test detection with controlPin unplugged everything works fine. But when controlPin is connected, value which is read inside the interrupt becomes wrong! So my dimmer cannot detect any half-wave and reports errors. This happens at the moment when controlPin value is set to HIGH with help of digitalWrite() func. After nearly 40-50 milliseconds detected values go back to normal, so most of time my dimmer work as expected.

I measured current on the controlPin, it's only 3.2mA, which is lower than maximum possible current for Arduino Due.

I tested this with detectorPin = 51, and different controlPins: 52, 36, 31.

So, how do you think, what is the problem? Is my Arduino broken?


texts: Get ESP32 Chip ID into a string variable (Arduino/C++ newbie here)

texts:
It's just a few days since I started using Arduino IDE ( programming an ESP32 ). As I learn, I am trying to write some snippets. I wanted to store the Chip ID of ESP32 into a variable (preferably string?) so that I can generate an unique device name. I looked through the ESP32 example programs and came across this program which just prints the Chip ID to the serial console.

  uint64_t chipid;

  chipid = ESP.getEfuseMac(); //The chip ID is essentially its MAC address(length: 6 bytes).
  Serial.printf("ESP32 Chip ID = %04X", (uint16_t)(chipid >> 32)); //print High 2 bytes
  Serial.printf("%08X\n", (uint32_t)chipid); //print Low 4bytes.

Now this works fine but I needed to store it into a variable in the following format "ESP32-0A1B3C4D5E6F" ( the last part of which is the Chip/MAC ID which is 6 bytes ). I went about some reading and currently reading and managed to get this far

  char ssid1[15];
  char ssid2[15];

  uint64_t chipid = ESP.getEfuseMac(); // The chip ID is essentially its MAC address(length: 6 bytes).
  uint16_t chip = (uint16_t)(chipid >> 32);

  snprintf(ssid1, 15, "%04X", chip);
  snprintf(ssid2, 15, "%08X", (uint32_t)chipid);

  Serial.print(ssid1);
  Serial.println(ssid2);

I am trying to read this which seems to be an excellent article on handling Arduino strings but just being a few days old with Arduino/c++ I am having some difficulty in wrapping my head around some of the concepts. I come from a Python, PHP, Javascript background so I guess this is gona take a little bit of a time. I am getting the output that I want in the serial console but now I would need this in this format (MCUDEVICE-0A1B3C4D5E6F). I am sure this code can be written in a much nicer, cleaner manner but for now I need this to proceed with another snippet (which relies on device name in the above mentioned format). Can anyone provide some pointers while I try check out the different ways I could achieve this? I just want to be sure that I am not writing ugly (and dangerous code - crashes, buffer overruns etc). Greatly appreciate any pointers. I guess I am starting to get a little paranoid about handling strings ( especially on low memory devices like typical mcus ).


texts:
My arduino robot has two dc motors as two wheels and have mounted an IR led on it. I get current position of the robot as (x,y) coordinates in the arena using camera which is mounted at the top of the arena..

My robot communicates with PC through bluetooth. I can read current position of robot on pc with the help of camera. Robot uses arduino motor shield to drive DC motors.

Which is the best method to move robot through the waypoints for a robot with DC motors without encoders?


texts:
I need help on how to select camera for transmitting video through Wi-Fi or RF module to my laptop.
How to select proper camera?
How to select adequate Wi-Fi or RF module for it?
I will be using Arduino mega for this.
thanks in advance.


texts: I set up a simple code to tell me if the button was pressed or not. When I get within a foot of the Arduino the button triggers. I first noticed this when trying to trigger a servo with a button. I've now had 3 different Arduinos, and every time if there is any button input, when I get close it says the button is pressed. I've searched this everywhere and can't find the reason. If anyone has any remote idea please tell me.


texts: Trying to start a timer to change lights when a button is pressed

texts:
I am trying to setup a series of lights (traffic lights) that change based on a timer that begins when a button is pressed.  The goal is to use the lights to track how long its been since you pressed the button.

The issue I am running into is trying to use the "TimeAlarms" library.  I am getting an error
'Timer' was not declared in this scope

I think it may be an issue with the version of Arduino I am using (1.6.8) but I am not sure.

Board: Arduino Leonardo

Here the code:

#include <TimeAlarms.h>
#include <Time.h>
#include <TimeLib.h>

int redPin = 2;
int yellowPin = 3;
int greenPin = 4;
int buttonPin = 5;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial) ;
  pinMode(redPin, OUTPUT);
  pinMode(yellowPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  // set timers in seconds, yellow = 24 hours, red = 48 hours)
  // http://www.pjrc.com/teensy/td_libs_TimeAlarms.html
  Alarm.timerOnce(86400, YellowTimer);
  Alarm.timerOnce(172800, RedTimer);

}

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(buttonPin))
  {
      setLights(LOW, LOW, HIGH)
      void YellowTimer(){
         setLights(LOW, HIGH, LOW)
         }
      void RedTimer(){
         setLights(HIGH, LOW, LOW)
         }
  }
  delay (1000);
  }

void setLights(int red, int yellow, int green)
{
  digitalWrite(redPin, red);
  digitalWrite(yellowPin, yellow);
  digitalWrite(greenPin, green);
}

Any help would be greatly appreciated.


texts:
I'm trying to connect a 2.8" display but it uses all the pins. That similar to this post (here: 2.8" TFT Touchscreen Prohibits Access to Unused Pins)

However, they recommend a proto screw shield (show here: http://www.mouser.com/ProductDetail/Adafruit/196/?qs=GURawfaeGuDa14An8N8oeg%3D%3D&gclid=CKjBqd2xpMgCFQiVfgodN5wCbA&kpid=1480459155)

However, how would that work? I'm a bit of a noob -- does anyone have any diagrams of it being connected, etc?

Thanks!


texts: Error in my Arduino code " error: expected unqualified-id before ‘if’ "

texts:
I cant seem to find this error is:

elevator_bug_2.ino:38:1: error: expected unqualified-id before ‘if’

Here is the code:

// these constants won't change. They are the
// lowest and highest readings you get from your sensor:
const int sensorMin = 0;      // sensor minimum, discovered through experiment
const int sensorMax = 600;    // sensor maximum, discovered through experiment

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the sensor:
  int sensorReading = analogRead(A0);
  // map the sensor range to a range of four options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 3);

  // do something different depending on the
  // range value:
  switch (range) {
    case 0:    // your hand is on the sensor
      Serial.println("dark");
      break;
    case 1:    // your hand is close to the sensor
      Serial.println("dim");
      break;
    case 2:    // your hand is a few inches from the sensor
      Serial.println("medium");
      break;
    case 3:    // your hand is nowhere near the sensor
      Serial.println("bright");
      break;
  }
  delay(1);        // delay in between reads for stability
}

if (Serial.println("dark") == true)   // LINE 38
{

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by

// the setup routine runs once when you press reset:
void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}
}


texts:
I am new to Arduino and I have the following:

int     delaynum;
char    cval[12];

void setup()
{
 Serial.begin(9600);
 Serial.print("Enter Number");
 Serial.flush();

 int i=0;
 while(i<12)
 {
  if(Serial.available()>0)
  {
    char ch=Serial.read();
    if(ch>='0'&&ch<='9')
    {
      cval[i]=ch;
      i++;
    }
    else
    {
      cval[i]=0;
      delaynum=atoi(cval);
      break;
    }
  }
 }
}
void loop()
{
   Serial.println(delaynum);
   exit(0);
}

The code output in virtual bread board:(i Entered 100)

But when i remove Serial.flush() The output like (i Entered 100)

I am Expecting the output:

Enter Number (I want to enter number 100 after the output)

100

Why the code not working ?

I am using Arduino IDE with virtual bread board(ATMega328p)


texts: Why do I get access denied when I do have mysql root user added to grant all privileges?

texts:
I am using the below mysql example sketch to upload data directly to mysql db.

#include "SPI.h"
#include "Ethernet.h"
#include "sha1.h"
#include "mysql.h"

/* Setup for Ethernet Library */
byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 1, 177);
IPAddress server_addr(192, 168, 1, 3);
//char server_addr[] = "192.168.1.3";

/* Setup for the Connector/Arduino */
Connector my_conn; // The Connector/Arduino reference

char user[] = "root";
char password[] = "secret";
char INSERT_SQL[] =
 "INSERT INTO test_arduino.hello VALUES ('Hello, MySQL!', NULL)";

void setup() {
  Ethernet.begin(mac_addr, ip);
  Serial.begin(9600);
  delay(1000);
  Serial.println("Connecting...");
  if (my_conn.mysql_connect(server_addr, 3306, user, password))
  {
    delay(500);
    Serial.println("Connection Successfull,inserting to database.");
     /* Write Hello, World to MySQL table test_arduino.hello */
     my_conn.cmd_query(INSERT_SQL);
     Serial.println("Query Success!");
  }
  else
    Serial.println("Connection failed.");
}

void loop() {
}

I am getting the error in serial Monitor:

  Connecting...

  Error: 76 = Access denied for user
  'root'@'192.168.1.177' (using password: YES).

  Connection failed.

even when I have all prvialages on root user for the ip of client !

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.1.177';
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT host FROM mysql.user WHERE User = 'root';
+---------------+
| host          |
+---------------+
| 127.0.0.1     |
| 192.168.1.177 |
| ::1           |
| localhost     |
| raspberrypi   |
+---------------+
5 rows in set (0.00 sec)

I ran the following query :

mysql> SELECT SUBSTRING_INDEX(USER(), '@', -1) AS ip,  @@hostname as hostname, @@port as port, DATABASE() as current_database;

and got the below result !

+-----------+----------+------+------------------+
| ip        | hostname | port | current_database |
+-----------+----------+------+------------------+
| localhost | ceres    | 3306 | test_arduino     |
+-----------+----------+------+------------------+
1 row in set (0.00 sec)

however I am trying to access the test_arduino database from a different IP other than the one mentioned above, does that mean where it says localhost, it is supposed to have 192.168.1.177 as well ? if so How do I insert ip to database test_arduino ?

then what am I missing ? please help.


texts:
I'm playing around with a SparkFun Redboard (essentially, an Arduino UNO).

I have a simple 5V sensor that I'd been trying to get to work with A2 and analogRead(). Nothing seemed to work. It's supposed to be cycling from 0 to 5V, which should give me values from 0 to 1023, and instead I get constant values of around 260.

In desperation, I tried using other ports. On A0, A1, and A3 I get the signals I expect. On A2, still nada.

So, the question. Is there something I could have done in configuring things that would have made A2 and only A2 stop reading correctly? If so, how can I reset it?

Or is there some other function that I might be using that could interfere with A2? Currently, I'm only using Serial over USB - could that interfere with A2?

Or could I simply have fried the port?


texts:
How to set computer time on Arduino Uno, and then control it (Arduino) with Serial monitor. For example show time on LCD.

I have no idea, how to make it using Arduino IDE. So, maybe I can write code in IDE, then load on Arduino. And with some script run Serial monitor also sending current time?

P.S. I have no additional boards like RTC or Ethernet.


texts: My LED display fails with MSGEQ7 output stuck

texts:
I have an Arduino setup with a pro-mini, a MSGEQ7, and a auto-gain mic. Even if I remove the audio input to the MSGEQ7 remains the same in the 890s (out of 1024). It's the same on each of two new MSGEQ7. I've checked the schematics, https://www.instructables.com/Music-Sync-Flashing-LEDs-Arduino-MSGEQ7/, multiple times and everything seems in order including components.
I'm using the #include <MD_MSGEQ7.h>, but I've tried it without.
Any ideas?
#include <Adafruit_NeoPixel.h>
#include <MD_MSGEQ7.h>

int LEDPIN = 12;
int MODEPIN = 10;

int mode = 0;
int lastState = LOW;

int NUMPIXELS = 50;

int DATA_PIN = 1; // read from multiplexer using Analog Pin 1, MSGEQ7 pin 3
int STROBE_PIN = 2; // MSGEQ7 pin 4
int RESET_PIN = 3; // MSGEQ7 pin 7

int spectrumValue[7];

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, LEDPIN, NEO_GRB + NEO_KHZ800);
MD_MSGEQ7 MSGEQ7(RESET_PIN, STROBE_PIN, DATA_PIN);

void setup() {

  Serial.begin(9600);
  pinMode(MODEPIN, INPUT);
  pixels.begin();
  MSGEQ7.begin();
}

void loop() {
  int currentState = digitalRead(MODEPIN);

  if (currentState == LOW && lastState == HIGH) {
    mode++;
    if (mode > 2) {
      mode = 0;
    }
  }
  lastState = currentState;

  MSGEQ7.read();

  for (int i = 0; i < 7; i++) {
    Serial.println(MSGEQ7.get(i));
  }
  if (mode == 0) {
    for (int i = 0; i < NUMPIXELS - 1; i++) {
      pixels.setPixelColor(i, pixels.Color(30, 60, 60)); // RGB
    }
  } else if (mode == 1) {/////////////////////////////////////////////////////////
    int height = (NUMPIXELS - 1) * MSGEQ7.get(1) / 1024;
    for (int i = 0; i < NUMPIXELS - 1; i++) {
      if (i < height) {
        pixels.setPixelColor(i, pixels.Color(60, 60, 0)); // RGB
      } else {
        pixels.setPixelColor(i, pixels.Color(0, 0, 0)); // RGB
      }
    }
  } else if (mode == 2) { /////////////////////////////////////////////////////////
    pixels.setPixelColor(0, pixels.Color(120 * MSGEQ7.get(5) / 1024, 0, 0)); // RGB
  }
  pixels.show();
}


texts: I need to sample voltage at a very high rate (say for like 10000 Hz) and with a very good precision(at least 10-12 bit ADC will do). So I am in need of an Analog-to-Digital Converter(ADC) which has a very high sampling rate (sampling rate has to be constant and known), can be interfaced with Arduino Mega or Raspberry Pi and noise should be neligible to minimum level of voltage magnitude that it can count. Can anyone suggests me with any ADC that follows these characteristics?


texts: In Linux, how do I get this Arduino library to work

texts:
In Linux Fedora 20 Arduino I want to use the Timer library from here, from which  I have downloaded the folder Timer-master.zip, but, when I try to import it, I get the Arduino message that it cannot be imported because its name includes characters other than plain ACSII letters and numbers. I have tried copying the file to Timermaster.zip and importing that instead, but still got exactly the same failure message.

Please, how do I get out of this impasse?


texts: What value of resistance to put between the output of a 74hc595 and the LEDs?

texts:
I'm going to start a project to make an array of LEDs using the shift registers 74HC595, I've seen many tutorials and it's not really difficult using the Arduino plataform.

The situation is as follows: in the tutorials they put a resistance between the outputs of the 74HC595 (Qx) and the LEDs , but in each tutorial the resistance varies (between 200 and 575 Ohms).

Then the question would be: if feed with 5V to 74HC595 (the same power as the Arduino) and the resistance that I put between its outputs (Qx) and the LEDs is lower (let's say 200 Ohms), the LEDs will light brighter than if I do it with resistors with higher values (let's say 500 Ohms)?


texts: Is there any good working MODBUS TCP master library available for Arduino?

texts: I would like to connect with Fronius solar inverter through MODBUS TCP with Arduino to READ and WRITE register values only. I want to set the Arduino as master and the Inverter as slave. I want to use only two functions "Read Holding Registers" and "Write Single Holding Register" function code '3' and function code '6' respectively. Is there any good and working library available for these? And also an example.


texts: Gravity fan does not work when powered by 3.3V ESP8266

texts:
The gravity fan has 3 pins. I connected one pin to the ground, one pin to the digital pin numbered 2 on ESP8266. I uploaded this code but the fan doesn't run at all. The fan supposedly uses a 5V power supply but the ESP8266 only supplies 3.3V. Could this be the problem?

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

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


texts: Did I fry my Uno? Computer is no longer detecting the board

texts:
I'm very new to arduino and have recently encountered an issue where my board is no longer being detected on my computer (Mac OS High Sierra). The board seems to power on as usual and has lights showing on boot and when it's on.

What can I check to make sure I didn't fry the chip? I would think if I fried it, then nothing would happen when I plug it in.


texts: Error - invalid conversion from 'char' to 'const char*', Not able to connect on pubnub server using node mcu

texts:
I have node mcu with ESP8266 wifi module. When i am trying to upload an example code then its not working.

This is the Error:-

inline PubSubClient* PubNub::subscribe(const char* channel, int timeout)

                      ^

exit status 1
invalid conversion from 'char' to 'const char*' [-fpermissive]

Code:-

#include <ESP8266WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP

#include <PubNub.h>

const char *ssid =  "mym404";     // replace with your wifi ssid and wpa2 key
const char *pass =  "786110786";

char pubkey = 'pub-c-4a9cdbca-5688-4939-a852-f63cf6743980';
char subkey = 'sub-c-9b4067ae-1293-11e9-b4a6-026d6924b094';

char pubchannel = 'demo_keyset';
char subchannel = 'demo_keyset';

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(9600);

       Serial.println("Connecting to ");
       Serial.println(ssid);

       WiFi.begin(ssid, pass);
       while (WiFi.status() != WL_CONNECTED)
          {
            delay(500);
            Serial.print(".");
          }
      Serial.println("");
      Serial.println("WiFi connected");

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(pubkey, subkey);
}

void loop() {
    /* Maintain DHCP lease. For other HW, you may need to do
       something else here, or maybe nothing at all. */

    /* Publish message. You could use `auto` here... */
    PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"message\"");
    if (!pclient) return;
    PublishCracker cheez;
    cheez.read_and_parse(pclient);
    /** You're mostly interested in `outcome()`, and,
        if it's "failed", then `description()`.
    */
    Serial.print("Outcome: "); Serial.print(cheez.outcome());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
    Serial.print("description: "); Serial.println(cheez.description());
    Serial.print("timestamp: "); Serial.println(cheez.timestamp());
    Serial.print("state: "); Serial.print(cheez.state());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
    pclient->stop();

    /* Wait for news. */
    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    while (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
        }
    }
    sclient->stop();

    delay(1000);
}

Code is taken from pubnub arduino github example - https://github.com/pubnub/arduino/blob/master/examples/AdafruitFeatherM0WINC1500/AdafruitFeatherM0WINC1500.ino


texts: How to wire up 4-digit 7-segment display?

texts:
I have an Arduino Mega and the CL5642BH, a 4-digit 7-segment display. I found very helpful code here, but I don't understand how to wire it up on the breadboard.

The display has 12 pins: 6 on the top and 6 on the bottom. First I guess I need to find out which one is GND.

Then (see the link) there is this code:

int digit1 = 11; //PWM Display pin 1
int digit2 = 10; //PWM Display pin 2
int digit3 = 9; //PWM Display pin 6
int digit4 = 6; //PWM Display pin 8

int segA = A1; //Display pin 14
int segB = 3; //Display pin 16
int segC = 4; //Display pin 13
int segD = 5; //Display pin 3
int segE = A0; //Display pin 5
int segF = 7; //Display pin 11
int segG = 8; //Display pin 15

It's 11 pins, that's the correct amount so far. But how do I wire it up? The pins on the display are in no way labeled.

Note: I'm a software developer, but as far as electronics go, I'm still a beginner.


texts:
I'm trying to use a MIFARE 1K RFID card with RC522 RFID reader/writer for my college project.
I'm trying to understand about memory organization of MIFARE 1K.A documentation() that supplied with a RFID Arduino library() says like this.
I will very appreciate if someone explain me this portion clearly.

  The MIFARE Classic 1K offers 1024 bytes of data storage, split into 16 sectors; each sector is protected by two different keys, called A and B. Each key can be
  programmed to allow operations such as reading, writing, increasing valueblocks,
  etc. MIFARE Classic 4K offers 4096 bytes split into forty sectors, of which 32 are same size as in the 1K with eight more that are quadruple size sectors. MIFARE Classic mini offers 320 bytes split into five sectors.
  For each of these card types, 16 bytes per sector are reserved for the keys and access conditions and can not normally be used for user data. Also, the very first 16 bytes contain the serial number of the card and certain other manufacturer data and are read only. That brings the net storage capacity of these cards down to 752 bytes for MIFARE Classic 1k, 3440 bytes for MIFARE Classic 4k, and 224 bytes for Mini. It uses an NXP proprietary security protocol (Crypto-1) for authentication and ciphering.

Accordind to above quote,

  For each of these card types, 16 bytes per sector are reserved for the keys and access conditions and can not normally be used for user data.
  Blockquote

Explain how to divide 1024 bytes like this.It has 16 sectors.So,total memory should be 16*16=256 bytes.This is impossible. Please explain this.


texts:
I have an SPI 128x64 OLED display. Is it safe to power this display's VCC from a digital I/O pin? I would like to do this so I can connect it flush to my arduino's header, and so I can control the power going to the display for a "low power" sleep mode.

Thanks for any responses.


texts:
I have an Arduino Yún running Openwrt-Yún 1.5.3 (which is the latest version, as I upgraded yesterday), and I am trying to obtain a .hex (compiled sketch), so that I can upload a sketch directly into the Yún. I know about compiled sketches, but there are no build directories in "C:\Documents and Settings\MY_USERNAME\Local Settings\Temp".

Where can I obtain the .hex of any file I have compiled, and how?


texts:
As part of a larger project, I'm trying to create a simple template function that will take an array and a value, both of the same type, and fill the array with the value. I'm running into the error quoted below:

"specializing member '::Fill_With' requires 'template<>' syntax"

Below is the offending code fragment:

// Simple function to fill an array with a specified value.
template <class T> void Fill_With(T target_array, T value){
    int Array_Size = sizeof(target_array) / sizeof(T);
    for(int l = 0; l < Array_Size; ++l){
        target_array[l] = value;
    }
}

int array1[4] = {1,2,3,4}, k = 0;
Fill_With<int>(array1, k);

I've read numerous other forum posts on the error message, but haven't quite been able to figure out what I'm missing. I've read that I need to include a blank "template<>" header before the function declaration but that didn't seem to solve the issue.
What am I doing wrong? Thanks!


texts: AT42QT1070 sensor output issues in standalone mode

texts:
Also when I am trying to see the data read on pins in serial monitor, it is not reading as required. The code i am using is as follows:
const int tuch_Pin0=18;
const int tuch_Pin1=19;
const int tuch_Pin2=21;
const int tuch_Pin3=22;
const int tuch_Pin4=32;

int State1=0;
int State2=0;
int State3=0;
int State4=0;
int State5=0;

void setup() {
  Serial.begin(38400);
  pinMode( tuch_Pin0,INPUT);
  pinMode( tuch_Pin1,INPUT);
  pinMode( tuch_Pin2,INPUT);
  pinMode( tuch_Pin3,INPUT);
  pinMode( tuch_Pin4,INPUT);
}

void loop() {

    State1= digitalRead(tuch_Pin0);
    State2= digitalRead(tuch_Pin1);
    State3= digitalRead(tuch_Pin2);
    State4= digitalRead(tuch_Pin3);
    State5= digitalRead(tuch_Pin4);

    if( State1!=0){

         Serial.println("Touch0 press");
    }
    else if(State2!=0)
    {
      Serial.println("Touch1 press");
    }
     else if(State3!=0)
     {
         Serial.println("Touch2 press");
     }

     else if(State4!=0)
     {
       Serial.println("Touch3 press");
     }
   else if ( State5!=0)
   {
    Serial.println("Touch4 press");
   }
   else
   {
    Serial.println("please press any key");
   }
   delay(100);
}

.....................the output it shows is... touch press 0.. without any touch and shows press any key when I touch any pin. Where I am wrong? Any solution, please?


texts:
I'm working with arduino nano and it has interfaced with SIM900 GSM. I'm sending "AT\r" to GSM modem, but not getting response.

void setup()
{
  Serial.begin(9600);
  Serial.println("Setup is Ready");
}

void loop()
{
   Serial.write("AT\r");
   delay(1000);
   if(Serial.available() > 0)
   {
     Serial.println("Data received");
     Serial.println(Serial.read());
   }

}

Serial monitor:

Setup is Ready

ATATATATATATATATATATATATATATATATATAT

I've set the 9600 baudrate to modem and my rx and tx is connected correctly...
What is the problem?

Thanks


texts:
I'm on a Mac, running 10.11.6 and Arduino IDE 1.8.1.

I've been prototyping some projects using an Adafruit Trinket. I was not having any problems, until at some point my Mac stopped recognizing the trinket. Somewhere within that time, I installed the Digispark board and tested that as well. I also may have made some updates to the OS version.

I've tried many things to fix it including installing the FTDI drivers, plugging and unplugging. Restarts etc. Nothing seems to fix the issue. The board shows up in the system profiler, as well as USB Prober, but does not show as an option in the Arduino IDE. I've also tried using several different cables but no dice.

It's really frustrating, I'm not sure what else I can do to track the issue down.