Arduino reads the same in potentiometer - arduino

This is the code I used
float vl0, vl1, vl2 =0; // Variable para almacenar el voltaje
void setup() {
Serial.begin(9600); // Inicializamos la comunicación serial
}
void loop() {
v0 = analogRead(A0); // Leemos del pin A0 valor
v1 = analogRead(A1); // Leemos del pin A1 valor
v2 = analogRead(A2); // Leemos del pin A2 valor
vl0 = (v0*5.00/1023.00); // Calculamos el voltaje
vl1 = (v1*5.00/1023.00); // Calculamos el voltaje
vl2 = (v2*5.00/1023.00); // Calculamos el voltaje
Serial.print(vl0);
Serial.print("V");
Serial.print ("/");
Serial.print(vl1);
Serial.print("V");
Serial.print ("/");
Serial.print(vl2);
Serial.print("V");
Serial.println ("/");
delay(1000);
}
This is the output
enter image description here
As you can see it measures the same, and only alters when I move one potentiometer, Im new on this arduino thing.
I expected to yall can help me and give me some advices, I dont understand this language very well

Use this sketch until you manage to attach a pot to your pin A0
void setup() {
Serial.begin(9600); // Inicializamos la comunicación serial
}
void loop() {
Serial.println(analogRead(A0)); // Leemos del pin A0 valor
delay(500);
}

Related

LED brightness control using rotary encoder

I want to make a circuit where I have to use a rotary encoder to control the brightness of LEDS. I managed to get a single LED to work, but when trying to connect 6 more LEDs I can't seem to get it to work.
My setup basic: https://imgur.com/a/Idxcuqi (as the note says, I have a 5 pin Encoder, only a six pin was available)
int Brightness = 120;
int StepBrightness = 10;
unsigned long RealTime;
unsigned long CyclicTime;
const int pin_A = 2; // pin 2 de CLK aansluiting van de Rotary encoder
const int pin_B = 3; // pin 3 De DT aansluiting van de Rotary encoder
unsigned char encoder_A;
unsigned char encoder_B;
unsigned char encoder_A_vorige=0;
void setup() {
pinMode(9, OUTPUT); //I can only get pin 9 and no other pins work if I put different digit
pinMode(pin_A, INPUT);
pinMode(pin_B, INPUT);
RealTime = millis();
CyclicTime = RealTime;
}
void loop() {
RealTime = millis();
if(RealTime >= (CyclicTime + 5)){
encoder_A = digitalRead(pin_A);
encoder_B = digitalRead(pin_B);
if((!encoder_A) && (encoder_A_vorige)){
if(encoder_B) {
if(Brightness + StepBrightness <= 255) Brightness += StepBrightness;
}
else {
if(Brightness - StepBrightness >= 0) Brightness -= StepBrightness;
}
}
encoder_A_vorige = encoder_A;
analogWrite(9, Brightness);
CyclicTime = RealTime;
}
}
You need to declare output pins and write to them using analog write which is now set to turn a single (9) pin and not a variable (the pin you would want to turn at that point).
For Arduino Uno, only the following pins have PWM -> 3, 5, 6, 9, 10, 11
Therefore, only these few pins will work with the analogWrite() function and the other pins are not.
You do not need to call pinMode() to set the pin as an output before calling analogWrite().

Not able to Receive subscribed Message with PubSubClient.h in Arduino WeMos D1 R32

I'm using Arduino Wemos Esp32 D1 R32.
I'm trying to make an MQTT connection between My Arduino board and a MQTT Broker.
When I try to send messages from my Arduino, It works just fine. (I'm using a pullup button to send a message.) Whenever I press the button a message is sent.
But when I try to read a message and write it on the Serial with the callback function it just doesn't work.
Could someone please help me with that issue?
Here is my code:
[code]
#include <ETH.h>
#include <WiFi.h>
#include <WiFiAP.h>
#include <WiFiClient.h>
#include <WiFiGeneric.h>
#include <WiFiMulti.h>
#include <WiFiScan.h>
#include <WiFiServer.h>
#include <WiFiSTA.h>
#include <WiFiType.h>
#include <WiFiUdp.h>
#include <PubSubClient.h>
#define BUFFER_SIZE 100
#define pinBotao1 25 //input botao pullup
#define led 26 //output acende led
#define pot 4 //input Resistor
//WiFi
const char* SSID = "******"; // SSID / nome da rede WiFi que deseja se conectar
const char* PASSWORD = "******"; // Senha da rede WiFi que deseja se conectar
WiFiClient wifiClient;
//MQTT Server
const char* BROKER_MQTT = "mqtt.eclipse.org"; //URL do broker MQTT que se deseja utilizar
int BROKER_PORT = 1883; // Porta do Broker MQTT
#define ID_MQTT "BCI0111"
#define TOPIC_PUBLISH "BCIBotao111"
PubSubClient MQTT(wifiClient); // Instancia o Cliente MQTT passando o objeto espClient
//Declaração das Funções
void mantemConexoes(); //Garante que as conexoes com WiFi e MQTT Broker se mantenham ativas
void conectaWiFi(); //Faz conexão com WiFi
void conectaMQTT(); //Faz conexão com Broker MQTT
void enviaPacote(); //Envia uma mensagem ao Broker.
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void setup() {
pinMode(pinBotao1, INPUT_PULLUP);
pinMode(led, OUTPUT);
Serial.begin(115200);
conectaWiFi();
MQTT.setServer(BROKER_MQTT, BROKER_PORT);
MQTT.setCallback(callback);
}
void loop() {
mantemConexoes();
enviaValores();
MQTT.loop();
}
void mantemConexoes() {
if (!MQTT.connected()) {
conectaMQTT();
}
conectaWiFi(); //se não há conexão com o WiFI, a conexão é refeita
}
void conectaWiFi() {
if (WiFi.status() == WL_CONNECTED) {
return;
}
Serial.print("Conectando-se na rede: ");
Serial.print(SSID);
Serial.println(" Aguarde!");
WiFi.begin(SSID, PASSWORD); // Conecta na rede WI-FI
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
WiFi.begin(SSID, PASSWORD);
}
Serial.println();
Serial.print("Conectado com sucesso, na rede: ");
Serial.print(SSID);
Serial.print(" IP obtido: ");
Serial.println(WiFi.localIP());
}
void conectaMQTT() {
while (!MQTT.connected()) {
Serial.print("Conectando ao Broker MQTT: ");
Serial.println(BROKER_MQTT);
//if (MQTT.connect(ID_MQTT,USER_MQTT,PASSWORD_MQTT)) {
if (MQTT.connect(ID_MQTT)) {
Serial.println("Conectado ao Broker com sucesso!");
}
else {
Serial.println("Nao foi possivel se conectar ao broker.");
Serial.println("Nova tentativa de conexao em 10s");
delay(10000);
}
}
}
void enviaValores() {
bool estadoBotao1;
int estadoPot;
estadoBotao1 = digitalRead(pinBotao1);
estadoPot = char(analogRead(pot));
if (estadoBotao1==LOW) {
//Botao Apertado
MQTT.publish(TOPIC_PUBLISH, "estadoPot");
Serial.println("Botao1 APERTADO. Payload enviado.");
}
delay(1000);
}
You need to subscribe to one or more topics to receive messages. Typically you subscribe to the topic(s) you are interested in after connecting to MQTT, but you may also subscribe at other times based on your app's logic.
In this case you can change conectaMQTT like this:
void conectaMQTT() {
while (!MQTT.connected()) {
Serial.print("Conectando ao Broker MQTT: ");
Serial.println(BROKER_MQTT);
//if (MQTT.connect(ID_MQTT,USER_MQTT,PASSWORD_MQTT)) {
if (MQTT.connect(ID_MQTT)) {
Serial.println("Conectado ao Broker com sucesso!");
if (MQTT.subscribe(TOPIC_SUBSCRIBE)) {
Serial.println("Succesful subscription.");
} else {
Serial.println("Subscription failed.");
}
}
else {
Serial.println("Nao foi possivel se conectar ao broker.");
Serial.println("Nova tentativa de conexao em 10s");
delay(10000);
}
}
}

CASE stepper IR remote and Arduino

This is my code and i want to control stepper with IR remote. My code work fine but i want to know how can continu my action while a hold button on remote. The HEX code is different when i hold button and i don't know to recall my last function.
#include <boarddefs.h>
#include <ir_Lego_PF_BitStreamEncoder.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <Stepper.h>
int dir;
int receiver = 6; // Signal Pin of IR receiver to Arduino Digital Pin 6
IRrecv irrecv(receiver); // create instance of 'irrecv'
decode_results results; // create instance of 'decode_results'
const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution
// for your motor
// Ici c'est la nouvelle séquence que j'ai trouvé pour faire fonctionné le moteur (KP4M2) correctement avec le connecteur.
// Reste à mettre dans le bon ordre
Stepper myStepper(stepsPerRevolution, 2, 3, 4, 5);
void setup() {
irrecv.enableIRIn(); // Start the receiver
// set the speed at 60 rpm:
myStepper.setSpeed(100);
// initialize the serial port:
Serial.begin(9600);
}
void loop() {
if (irrecv.decode(&results)) // have we received an IR signal?
{
switch (results.value)
Here, i start switch with my HEX code fron IR remote
{
case 0xB4B49A65:
//myStepper.step(stepsPerRevolution);//counter clockwise rotation
//break;
VrDroite();
break;
case 0xB4B45AA5:
//myStepper.step(-stepsPerRevolution);//counter clockwise rotation
//break;
VrGauche();
case 0xB4B41AE5:
//myStepper.step(-stepsPerRevolution/10);//counter clockwise rotation
//break;
VrMicro();
}
irrecv.resume(); // receive the next value
Serial.println(results.value, HEX);
}
}
Use function for calling action
void VrDroite() {
myStepper.step(+100);
}
void VrGauche() {
myStepper.step(-stepsPerRevolution);//counter clockwise rotation
}
void VrMicro() {
myStepper.step(stepsPerRevolution / 10); //counter clockwise rotation
}
void VrNone() {
myStepper.step(0);
}enter code here
Thank
Try this.
This will remember your last keypress.
If the current keypress is a "hold", it will run the same function as the last keypress
#include <boarddefs.h>
#include <ir_Lego_PF_BitStreamEncoder.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <Stepper.h>
int dir;
int receiver = 6; // Signal Pin of IR receiver to Arduino Digital Pin 6
IRrecv irrecv(receiver); // create instance of 'irrecv'
decode_results results; // create instance of 'decode_results'
// last keypress value
unsigned long prev_result_value = 0;
// this key press value
unsigned long current_result_value;
const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution
// for your motor
// Ici c'est la nouvelle séquence que j'ai trouvé pour faire fonctionné le moteur (KP4M2) correctement avec le connecteur.
// Reste à mettre dans le bon ordre
Stepper myStepper(stepsPerRevolution, 2, 3, 4, 5);
void setup() {
irrecv.enableIRIn(); // Start the receiver
// set the speed at 60 rpm:
myStepper.setSpeed(100);
// initialize the serial port:
Serial.begin(9600);
}
void loop() {
if (irrecv.decode(&results)) { // have we received an IR signal?
current_result_value = results.value; // store the result
if (!prev_result_value)
prev_results_value = current_result_value; // first time through only.
if (results.value == HOLD_CODE) // is this a hold code?
current_results_value = rev_results_value; // make the current result the same as the last keypress.
//switch (results.value) {
switch (current_results_value) {
case 0xB4B49A65:
//myStepper.step(stepsPerRevolution);//counter clockwise rotation
//break;
VrDroite();
prev_results_value = current_results_value;
break;
case 0xB4B45AA5:
//myStepper.step(-stepsPerRevolution);//counter clockwise rotation
//break;
VrGauche();
prev_results_value = current_results_value;
case 0xB4B41AE5:
//myStepper.step(-stepsPerRevolution/10);//counter clockwise rotation
//break;
VrMicro();
prev_results_value = current_results_value;
}
irrecv.resume(); // receive the next value
Serial.println(results.value, HEX);
Serial.println(current_results_value, HEX);
Serial.println(prev_results_value, HEX);
}
}
void VrDroite() {
myStepper.step(+100);
}
void VrGauche() {
myStepper.step(-stepsPerRevolution);//counter clockwise rotation
}
void VrMicro() {
myStepper.step(stepsPerRevolution / 10); //counter clockwise rotation
}
void VrNone() {
myStepper.step(0);
}

arduino+Esp8266 + apk (TCP server-client)

someone know how i can do a correct comunication with esp8266 and apk (tcp server<->tcp client)
Here is the problem:
I send values and esp8266 dont read it well sometime;
arduino bauidio:115200
esp8266 baudio:115200
apk: send msg like 5;del;45 (speed,state,servo_position)
this is my car code (tcp server):
#include <SoftwareSerial.h>
#include <Servo.h>
#define M_ATRAS 4
#define M_ADELANTE 5
#define M_VELOCIDAD 6
Servo servo; // Crea un Objeto servo
SoftwareSerial ESP8266(3,2); //1)RX-> Azul, 2)TX->Amarillo
String mar;
int vel;
int rot;
void setup()
{
Serial.begin(9600);
ESP8266.begin(115200);
Serial.println("Iniciando...");
comandoESP("AT+RST"); // reset module
comandoESP("AT+CWMODE=3"); // configure as access point
//comandoESP("AT+CWSAP=\"ESP\",\"1234567890\",3,3"); //SSID,PASSWORD,CHANNEL,PASSWORD-ENCRYPATION(0=NO PASSWORD) //0 is encryption type like 0 = Open, 2 =WPA_PSK, 3 = WPA2_PSK, 4 = WPA_WPA2_PSK
comandoESP("AT+CWJAP=\"tfh\",\"fggrtfdfgdtg\"");
comandoESP("AT+CIPMUX=1"); // configure for multiple connections
comandoESP("AT+CIPSERVER=1,400"); // turn on server on port x
Serial.println("Servidor TCP ON...");
pinMode(M_VELOCIDAD, OUTPUT);
pinMode(M_ATRAS,OUTPUT);
pinMode(M_ADELANTE,OUTPUT);
velocidad(0);
servo.attach(7); // Selecionamos el pinde control para el servo Rango: 0<->155
Serial.println("Posicion delservo: "+String(servo.read()));
}
void loop()
{
if(ESP8266.available())
{
if(ESP8266.findUntil("+IPD,","."))
{
vel=ESP8266.readStringUntil(';').toInt();
mar=ESP8266.readStringUntil(';');
rot=ESP8266.readStringUntil(';').toInt();
velocidad( vel);
marcha(mar);
rotacion(rot);
Serial.println(String(vel)+"-"+mar+"-"+String(rot));
}
}
}
void marcha(String tipo){
if(tipo == "del")
{
//Serial.println("Adelante?");
digitalWrite(M_ATRAS,LOW);
digitalWrite(M_ADELANTE,HIGH);
}
else if(tipo == "tra")
{
//Serial.println("Atras?");
digitalWrite(M_ATRAS,HIGH);
digitalWrite(M_ADELANTE,LOW);
}
}
void velocidad(int v){
//Serial.println("Velocidad: "+String(v));
analogWrite(M_VELOCIDAD, v);
}
void rotacion(int r){
int rot =map(r,-10, 10, 125, 0); //mapeamos los valores que puede tener el acelerometro a los valores que puede tener el servo
//Serial.println("Acelerometro: "+String(r)+" Servo: "+String(rot));
servo.write(rot);
}
void comandoESP(String cmd)
{
ESP8266.println(cmd);
if(ESP8266.available())
Serial.println(ESP8266.readStringUntil(14));
delay(1000*3); //3seg
}
Instead of writing your own AT Commands, use a library and use Virtual Serial.
WeeESP8266 is a nice library. See my post on how to put all together.

XBee not communicating with Arduino connected

I have two XBee S2 modules. Both are communicating when I connect them directly to my computer and check via X-CTU terminal. The problem is when I try to send data wirelessly by connecting both of them with two Arduinos there is no communication at all. It doesn't send any value.
This is the code for the receiving side:
#include <SoftwareSerial.h>
SoftwareSerial XBSerial = SoftwareSerial(2, 3);
int BackMotorForward = 6;
int BackMotorReverse = 5;
int FrontMotorRight = 10;
int FrontMotorLeft = 9;
int sv1 = 0;
int sv2 = 0;
void setup ()
{
pinMode(BackMotorForward, OUTPUT); // Initialize the pin as an output.
pinMode(BackMotorReverse, OUTPUT); // Initialize the pin as an output.
pinMode(FrontMotorRight, OUTPUT); // Initialize the pin as an output.
pinMode(FrontMotorLeft, OUTPUT); // Initialize the pin as an output.
Serial.begin(9600);
// Set the data rate for the SoftwareSerial port
XBSerial.begin(9600);
// XBSerial.println(".");
}
void loop()
{
Serial.write(XBSerial.read());
if (XBSerial.available())
{
sv1 = XBSerial.read();
Serial.write(sv1);
}
if (XBSerial.available())
{
sv2 = XBSerial.read();
Serial.write(sv2);
}
if (sv1 < 280)
{
Serial.write("backward");
digitalWrite(BackMotorForward, HIGH);
digitalWrite(BackMotorReverse,LOW);
}
else if (sv1 > 380)
{
Serial.write("forward");
digitalWrite(BackMotorReverse,HIGH);
digitalWrite(BackMotorForward,LOW);
}
else
{
digitalWrite(BackMotorForward,LOW);
digitalWrite(BackMotorReverse,LOW);
}
if (sv2 > 380)
{
Serial.write("left");
digitalWrite(FrontMotorRight, HIGH);
digitalWrite(FrontMotorLeft,LOW);
}
else if (sv2 < 280)
{
Serial.write("right");
digitalWrite(FrontMotorLeft,HIGH);
digitalWrite(FrontMotorRight,LOW);
}
else
{
digitalWrite(FrontMotorRight,LOW);
digitalWrite(FrontMotorLeft,LOW);
}
}
This is the code for the sending side:
#include <SoftwareSerial.h>
SoftwareSerial XBSerial = SoftwareSerial(2, 3);
const int xpin = A0; // x-axis of the accelerometer
const int ypin = A1; // y-axis
void setup()
{
// Initialize the serial communications:
pinMode(xpin, INPUT); //x axis
pinMode(ypin, INPUT); //y axis
Serial.begin(9600);
Serial.println("testing");
// Set the data rate for the SoftwareSerial port
XBSerial.begin(9600);
XBSerial.println("testing!!!");
}
void loop()
{
// Print the sensor values:
Serial.print(analogRead(xpin));
Serial.print("\t");
Serial.print(analogRead(ypin));
// Print a tab between values:
Serial.print("\t");
Serial.println();
// Delay before next reading:
delay(100);
int val = analogRead(xpin);
int val2 = analogRead(ypin);
XBSerial.print(val); //Changed from write to print
XBSerial.print(val2);
}
Okay, it was a really stupid mistake. I was using softwareserial pins 2,3 for XBee, but instead I was connecting their pins directly to pin 0,1 (rx,tx) of the Arduino. That's the reason there was no communication.

Resources