I had the following script working fine after changing from sp.getc to sp.gets.
require "rubygems"
require "serialport"
require "data_mapper"
#params for serial port
port_str = "/dev/ttyACM0"
baud_rate = 19200
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE
sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
loop do
sp_char = sp.gets
if sp_char.start_with?("Time")
printf("%s", sp_char)
end
end
I then reloaded the Arduino with the following (which I thought was what I had anyway?)
//SMS Send and Receive program
//Using Mega 2560 & Elecrow SIM900 GSM Shield
//4 July 2013
int count = 0;
int sendCount=0;
int n_sms,x,sms_start;
char data[300];
void setup()
{
Serial1.begin(19200); // the GPRS/GSM baud rate
Serial.begin(19200); // the USB baud rate
Serial1.println("AT\r");
Serial1.flush();
delay(1000);
Serial1.println("AT+CMGF=1\r");
Serial1.flush();
delay(1000);
Serial.println("Text Mode Selected");
Serial.flush();
//sendSMS();
}
void loop()
{
if(sendCount>720) //approx 60 minutes between sends
{
//sendSMS();
sendCount=0;
}
else
Serial1.print("AT+CMGR=1\r"); //Reads the first SMS
Serial1.flush();
for (x=0;x < 255;x++){
data[x]='\0';
}
x=0;
do{
while(Serial1.available()==0);
data[x]=Serial1.read();
x++;
if(data[x-1]==0x0D&&data[x-2]=='"'){
x=0;
}
}while(!(data[x-1]=='K'&&data[x-2]=='O'));
data[x-3]='\0'; //finish the string before the OK
Serial.println(data); //shows the message
Serial.flush();
Serial1.print("AT+CMGD=1,4\r");
Serial1.flush();
delay(5000);
sendCount++;
}
void sendSMS()
{
Serial1.println("AT+CMGS=\"+64xxxxxxxxxx\"\r");
//Replace this number with the target mobile number.
Serial1.flush();
delay(1000);
Serial1.println("SA\r"); //The text for the message
Serial1.flush();
delay(1000);
Serial1.write(0x1A); //Equivalent to sending Ctrl+Z
}
Now I get the following error :
serial_arduino.rb:16:in block in <main>': undefined methodstart_with?'for nil:NilClass (NoMethodError)
from serial_arduino.rb:14:in loop'
from serial_arduino.rb:14:in'
If I remove the start_with? method, then all is fine. Testing with irb shows method is OK
irb(main):003:0> 'AT'.start_with? 'Time'
=> false
irb(main):004:0> 'Time:0902'.start_with? 'Time'
=> true
Appears to be related to Arduino or my vitualised Debian machine. I have got it going after rebooting VM and powering off Arduino.
Related
I am trying to create a server with a simple webpage using the ESP01s module. My pin connections are as follows:
ESP TX to Arduino Uno Tx pin
ESP RX to Arduino Uno Rx pin
ESP VCC to Uno 3.3V pin
ESP GND to Uno GND
ESP EN to Uno 3.3V through 10K resistor
I am using the Arduino IDE and serial to USB cable, when I run a blank program I can send AT commands to the ESP module with no issues.
However when I try to run a script to build and deploy the simple webpage, I either get one of two messages in the IDE serial monitor or nothing:
Unreadable characters - jibberish
Boot instructions
load 0x40100000, len 27728, room 16
tail 0
chksum 0x2a
load 0x3ffe8000, len 2124, room 8
tail 4
chksum 0x07
load 0x3ffe8850, len 9276, room 4
tail 8
chksum 0xba
csum 0xba
No output to serial monitor even though code uploads
This is my code:
#include <SoftwareSerial.h>
SoftwareSerial esp8266(0,1); // rx, tx;
#define serialCommunicationSpeed 115200
#define DEBUG true
void setup()
{
Serial.begin(serialCommunicationSpeed);
esp8266.begin(serialCommunicationSpeed);
InitWifiModule();
}
void loop() {
if (esp8266.available()) {
if (esp8266.find("+IPD,")) {
delay(1000);
int connectionId = esp8266.read() - 48;
String webpage = "<h1>Capstone Group 45: SolarFi</h1>";
String cipSend = "AT+CIPSEND=";
cipSend += connectionId;
cipSend += ",";
cipSend += webpage.length();
cipSend += "\r\n";
sendData(cipSend, 1000, DEBUG);
sendData(webpage, 1000, DEBUG);
String closeCommand = "AT+CIPCLOSE=";
closeCommand += connectionId; // append connection id
closeCommand += "\r\n";
sendData(closeCommand, 3000, DEBUG);
}
}
}
String sendData(String command, const int timeout, boolean debug) {
String response = "";
esp8266.print(command);
long int time = millis();
while ((time + timeout) > millis()) {
while (esp8266.available()) {
char c = esp8266.read();
response += c;
}
}
if (debug) {
Serial.print(response);
}
return response;
}
void InitWifiModule() {
sendData("AT+RST\r\n", 2000, DEBUG);
sendData("AT+CWJAP=\"USERNAME\",\"PASSWORD\"\r\n", 2000, DEBUG);
delay(3000);
sendData("AT+CWMODE=1\r\n", 1500, DEBUG);
delay(1500);
sendData("AT+CIFSR\r\n", 1500, DEBUG);
delay(1500);
sendData("AT+CIPMUX=1\r\n", 1500, DEBUG);
delay(1500);
sendData("AT+CIPSERVER=1,80\r\n", 1500, DEBUG);
}
I'm trying to turn on an LED connected to an Arduino from a ruby file, as well as sending a string from that Arduino to my ruby file / terminal. (I'm doing these two things separately, to avoid potential problems).
I'm using a USB port to connect Arduino - Computer, and the serialport gem. I'm working in Linux.
To receive the string on my computer:
I have followed several tutorials that all recommend to run this ruby file:
require 'serialport'
port_str = '/dev/ttyACM0'
baud_rate = 9600
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE
sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
while(true) do
message = sp.gets.chomp
puts message
end
And uploaded this to the Arduino:
uint8_t c;
int i;
void setup() {
Serial.begin(9600); // set baud rate
pinMode(13, OUTPUT); // set pin 13 to be output for LED
digitalWrite(13, LOW); // start with LED off
}
void loop() {
while (Serial.available() > 0) { // check if serial port has data
// writes to computer
Serial.println("Hello world");
}
}
I got this error message: undefined method `chomp' for nil:NilClass (NoMethodError). When getting rid of .chomp, at some point I could get some parts of "Hello world" being printed on my terminal, such as "Hell", and then far later "o w", etc.
Now I don't even get anything anymore.
To turn the led on:
In the ruby file, I replaced the message part by
sp.write('a')
And in the arduino file,
void loop() {
while (Serial.available() > 0) { // check if serial port has data
c = Serial.read(); // read the byte
if (c == 'a'){
digitalWrite(13, HIGH); // turn on LED
delay(500); // wait 500 milliseconds
digitalWrite(13, LOW); // turn off LED
delay(500); // wait 500 milliseconds
}
}
}
The led turns on if I remove the condition (c == 'a'), but obviously I need it if I want the arduino to perform different actions.
I'm new to Serial communication, so I'm not quite sure where the error comes from, since I feel somehow some data seems to be transmitted.
step by step what I did so far
1) micro controller used CC3200 from Texas instruments ( wifi builted micro controller)
2) Conductive rubber cord stretch sensor - connected to Microcontroller's analog pin
**Sensor's behaviour = ( resistance increases upon stretching the conductive rubber)
So now, following is the code fo reference which I debugged in to the microcontroller to run the sensor(Using energia tool-IDE).
The code is nothing but written for the web server( which I gave- available wifi ssid and password-which you can see in the following programm "iPhone and the passowrd"), where the sensor's code is also wrote in to,
And this webserver reads and generates IP address of the microcontroller and also values of the stretch sensor.
Webserver code :
#include <SPI.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
// which analog pin to connect
#define RUBBERPIN A3
// how many samples to take and average, more takes longer
// but is more 'smooth'
#define NUMSAMPLES 5
// the value of the 'other' resistor
#define SERIESRESISTOR 10000
int samples[NUMSAMPLES];
// your network name also called SSID
char ssid[] = "iPhone";
// your network password
char password[] = "123456789";
// your network key Index number (needed only for WEP)
int keyIndex = 0;
WiFiServer server(3000);
void setup() {
Serial.begin(115200); // initialize serial communication
analogReference(EXTERNAL);
pinMode(RED_LED, OUTPUT); // set the LED pin mode
// attempt to connect to Wifi network:
Serial.print("Attempting to connect to Network named: ");
// print the network name (SSID);
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP
network:
WiFi.begin(ssid, password);
while ( WiFi.status() != WL_CONNECTED) {
// print dots while we wait to connect
Serial.print(".");
delay(300);
}
Serial.println("\nYou're connected to the network");
Serial.println("Waiting for an ip address");
while (WiFi.localIP() == INADDR_NONE) {
// print dots while we wait for an ip addresss
Serial.print(".");
delay(300);
}
// you're connected now, so print out the status
printWifiStatus();
Serial.println("Starting dataerver on port 3000");
server.begin(); // start the web server on port
80
Serial.println("Dataserver started!");
}
void loop() {
// listen for incoming clients
WiFiClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
uint8_t i;
float average;
// take N samples in a row, with a slight delay
for (i=0; i< NUMSAMPLES; i++) {
samples[i] = analogRead(RUBBERPIN);
delay(10);
}
// average all the samples out
average = 0;
for (i=0; i< NUMSAMPLES; i++) {
average += samples[i];
}
average /= NUMSAMPLES;
Serial.println(average);
client.println(average);
delay(10);
}
delay(1);
// close the connection:
client.stop();
Serial.println("client disonnected");
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("Network Name: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
After running this programm it generates IP address and sensor's values(
221.40
221.20
221.20
*********here = value missing were a noise is visible on graph
221.00
221.20
221.40
221.00
221.20
221.40
221.00
221.40
221.20
221.40
221.20
221.00
221.00
221.60
221.00
221.20
*********here = value missing were a noise is visible on graph
221.20
221.00
Now,
I wrote the generated IP address in to a client programm (In the tool- named processing.org )
Here is my client code
import processing.net.*;
Client c;
String input;
int data[];
int posx;
void setup()
{
size(1000, 500);
background(204);
stroke(0);
frameRate(5); // Slow it down a little
// Connect to the server's IP address and port
c = new Client(this, "192.168.23.2", 3000); // Replace with your server's IP
and port
posx =2;
data = new int[3];
}
void draw()
{
posx++;
// Receive data from server
if (c.available() > 0) {
input = c.readString();
input = input.substring(0, input.indexOf("\n")); // Only up to the newline
println(input);
data[0]=data[1];
data[1] = int(input); // Split values into an array
// Draw line using received coords
stroke(0);
line(posx-1, data[0]+10, posx, data[1]+10);
}
}
My results after running the following programm:
Server sending the data and client receiving the data wirelessly- its all fine
I am able to see the output signal which I am expecting. i.e., when my sensor is in rest position the output must be straight line and if I stretch my sensor the voltage signal must increase- Iam able to see all these. But,
here is a small problem
There is a noise coming out from the output signal (please have a look in to the following picture.)
Noise
So my problem is even when the sensor is in rest position- with out any stretch- there is peak coming out.
please help me
I have compiled libzmq with openpgm with no changes under windows. Code here is taken from ZeroMQ Guide ("weather publisher" server/client). But if i change "tcp" to "epgm" it doesn't work any more (data is not received, but connection is established).
void test_serv()
{
// Prepare our context and publisher
void *context = zmq_ctx_new();
void *publisher = zmq_socket(context, ZMQ_PUB);
int rc = zmq_bind(publisher, "epgm://127.0.0.1:5556");
assert(rc == 0);
// Initialize random number generator
srandom((unsigned)time(NULL));
while (!stop_server)
{
// Get values that will fool the boss
int zipcode, temperature, relhumidity;
zipcode = randof(1000) + 600;
temperature = randof(215) - 80;
relhumidity = randof(50) + 10;
// Send message to all subscribers
char update[20];
sprintf(update, "%d %d %d", zipcode, temperature, relhumidity);
s_send(publisher, update);
}
LOG("END Server shutdown");
Sleep(500);
zmq_close(publisher);
zmq_ctx_destroy(context);
}
void test_sock()
{
// Socket to talk to server
LOG("Collecting updates from weather server...");
void *context = zmq_ctx_new();
void *subscriber = zmq_socket(context, ZMQ_SUB);
int rc = zmq_connect(subscriber, "epgm://127.0.0.1:5556");
assert(rc == 0);
// Subscribe to zipcode, default is NYC, 10001
char *filter = "1001 ";
rc = zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE,
filter, strlen(filter));
assert(rc == 0);
// Process 100 updates
int update_nbr;
long total_temp = 0;
for (update_nbr = 0; update_nbr < 10; update_nbr++) {
char *string = s_recv(subscriber);
int zipcode, temperature, relhumidity;
sscanf(string, "%d %d %d",
&zipcode, &temperature, &relhumidity);
total_temp += temperature;
LOG(">> " << string);
free(string);
}
LOG("Average temperature for zipcode "<< filter << "was " << (int)(total_temp / update_nbr) << 'F');
zmq_close(subscriber);
zmq_ctx_destroy(context);
}
I run two functions in different threads, with tcp anything works as expected.
I have tried doing "route print 0.0.0.0" with cmd.exe and using interface IP (192.168.137.64) as prefix instead of "eth0" like shown in RFC: epgm://192.168.137.64;127.0.0.1:5556 on connect and/or bind, but this brokes my socket and raises error.
Also "PGM" requires administrator rights and i cannot test it now.
The error IS NOT "protocol not supported" errno is set to B (11) and i don't understand what does it mean (no docs on it).
EPGM is a bit finicky. According to this list post, if you're using EPGM your publisher and subscriber must be on separate hosts. More details here, it looks like this was a deliberate choice by the ZMQ team.
So, try it by spinning up your PUB and SUB on separate machines (changing the network addresses accordingly, of course).
The reason might be that windows does not support loopback capture interface. I tried weather example with protocol changed to epgm on linux and it works fine (well, shows some warnings about loopback, but the messages are transfered correctly)
So I am trying to send data to my Arduino through a HC-05 Bluetooth Chip. I'm using Ruby, and so far, I get the error shown below. Any idea why? I'm using Windows 10
My arduino is on COM3 (USB) and the bluetooth chip is on COM37
Error 1
in `create': Permission denied - \\.\COM37 (Errno::EACCES)
If I try it again I get this error:
Error 2
in `create': Invalid argument - \\.\COM37 (Errno::EINVAL)
Ruby Code
require 'serialport'
puts "What COM Port?"
comport = gets.chomp
comport = comport.to_i
comport = comport -1
sp = SerialPort.new(comport,9600)
while 1
puts "What message do you want to send?"
write = gets.chomp
if write == "exit"
abort
end
sp.write write
end
Arduino Code
#include <Motor.h>
#include <SoftwareSerial.h>
Motor m8(8);
SoftwareSerial Bluetooth(12, 13); //12-TX 13-RX
// Declare a new 'char' or "character" that we will use to store the keyboard
// input sent to the bluetooth chip
char input;
boolean stop = false;
void setup() {
Bluetooth.begin(9600);
m8.attach();
}
void loop() {
// If there is input available on the bluetooth chip (that is, we sent a character
// to the chip from the computer)...
if (Bluetooth.available()) {
// Read the first available character from the bluetooth chip and store it in the
// 'input' variable
input = Bluetooth.read();
if (input == 'w') {
stop != stop;
}
if (input == 'd') {
m8.turn(100);
}
if (input == 'a') {
m8.turn(-100);
}
}
if (stop != true) {
m8.stop();
}
}
If I try to connect to my arduino using COM3 and USB, I don't get an error and it successfully sends data the the arduino.
Thanks in advance!